迭代Python中List对应的字典键值
使用 Python 2.7 工作。我有一个字典,其中团队名称作为键,每个团队得分和允许的跑动量作为值列表:
NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}
我希望能够将字典输入到函数中并迭代每个团队(键)。
这是我正在使用的代码。现在我只能一个队一个队的去。我将如何迭代每个团队并打印每个团队的预期 win_percentage ?
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
感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您有多种迭代字典的选项。
如果您迭代字典本身(
for team in league
),您将迭代字典的键。使用 for 循环进行循环时,无论是循环字典 (league
) 本身还是league.keys()
:您还可以通过迭代来一次迭代键和值league.items():
您甚至可以在迭代时执行元组解包:
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, orleague.keys()
:You can also iterate over both the keys and the values at once by iterating over
league.items()
:You can even perform your tuple unpacking while iterating:
您也可以非常轻松地迭代字典:
You can very easily iterate over dictionaries, too:
字典有一个名为
iterkeys()
的内置函数。尝试:
Dictionaries have a built in function called
iterkeys()
.Try:
字典对象允许您迭代它们的项目。另外,通过模式匹配和 __future__ 的划分,您可以稍微简化一些事情。
最后,您可以将逻辑与打印分开,以便以后更容易重构/调试。
Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from
__future__
you can do simplify things a bit.Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.
列表理解可以缩短事情......
List comprehension can shorten things...