在Python中对应于列表的词典键值迭代 [英] Iterating Over Dictionary Key Values Corresponding to List in Python

查看:129
本文介绍了在Python中对应于列表的词典键值迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中工作2.7。我有一个字典与团队名称作为关键,每个团队的得分和允许的数量作为价值表:

  NL_East = {'Phillies':[645,469],'Braves':[599,546],'Mets':[653,672]} 

我希望能够将字典提供给一个函数,并遍历每个团队(键)。



这是我正在使用的代码。现在,我只能按队去团队。如何迭代每个团队,并打印每个团队的预期win_percentage?

  def Pythag(联赛):
run_scored = float(league ['Phillies'] [0])
runs_allowed = float(league ['Phillies'] [1])$ ​​b $ b win_percentage = round((runs_scored ** 2)/((runs_cored ** 2)+(runs_allowed ** 2))* 1000)
打印win_percentage

感谢任何帮助。

解决方案

您有几个选项来迭代字典。



如果您迭代字典本身(为联盟中的团队),您将迭代字典的键。当循环使用for循环时,无论循环使用dict(联盟)本身,行为将是一样的, league.keys() league.iterkeys() dict.iterkeys() 通常是优先的,因为它是明确而有效的:

  for league.iterkeys():
run_scored,runs_allowed = map(float,league [team])

您还可以遍历两个键并且通过迭代 league.items() league.iteritems()

 用于团队,运行在league.iteritems()中:
runs_scored,runs_allowed = map(float,runs)

您甚至可以在迭代时执行元组拆包:



<$ p $
$ run_scored = float(runs_scored)
runs_allowed = float(runs_allowed)


Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list:

NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}

I would like to be able to feed the dictionary into a function and iterate over each team (the keys).

Here's the code I'm using. Right now, I can only go team by team. How would I iterate over each team and print the expected win_percentage for each team?

def Pythag(league):
    runs_scored = float(league['Phillies'][0])
    runs_allowed = float(league['Phillies'][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

Thanks for any help.

解决方案

You have several options for iterating over a dictionary.

If you iterate over the dictionary itself (for team in league), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league) itself, league.keys(), or league.iterkeys(). dict.iterkeys() is generally preferable because it is explicit and efficient:

for team in league.iterkeys():
    runs_scored, runs_allowed = map(float, league[team])

You can also iterate over both the keys and the values at once by iterating over league.items() or league.iteritems():

for team, runs in league.iteritems():
    runs_scored, runs_allowed = map(float, runs)

You can even perform your tuple unpacking while iterating:

for team, (runs_scored, runs_allowed) in league.iteritems():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

这篇关于在Python中对应于列表的词典键值迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆