Bur*_*ter 127 python dictionary loops function list
使用Python 2.7.我有一个字典,其中包含团队名称作为键,以及每个团队作为值列表得分和允许的运行量:
NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}
Run Code Online (Sandbox Code Playgroud)
我希望能够将字典输入函数并迭代每个团队(密钥).
这是我正在使用的代码.现在,我只能按团队一起去.我将如何遍历每个团队并为每个团队打印预期的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
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
And*_*ark 210
您可以通过多种方式迭代字典.
如果你遍历字典本身(for team in league),你将迭代字典的键.使用for循环进行循环时,无论是否遍历dict(league)本身,行为都是相同的,或者league.keys():
for team in league.keys():
runs_scored, runs_allowed = map(float, league[team])
Run Code Online (Sandbox Code Playgroud)
您还可以通过迭代迭代迭代键和值league.items():
for team, runs in league.items():
runs_scored, runs_allowed = map(float, runs)
Run Code Online (Sandbox Code Playgroud)
您甚至可以在迭代时执行元组解包:
for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)
Run Code Online (Sandbox Code Playgroud)
dan*_*cek 10
您也可以非常轻松地迭代字典:
for team, scores in NL_East.iteritems():
runs_scored = float(scores[0])
runs_allowed = float(scores[1])
win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
print '%s: %.1f%%' % (team, win_percentage)
Run Code Online (Sandbox Code Playgroud)
字典有一个内置的函数叫做iterkeys().
尝试:
for team in league.iterkeys():
runs_scored = float(league[team][0])
runs_allowed = float(league[team][1])
win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
print win_percentage
Run Code Online (Sandbox Code Playgroud)
字典对象允许您迭代其项目.此外,通过模式匹配和分割,__future__您可以简化一些事情.
最后,您可以将逻辑与打印分开,以便以后重构/调试更容易.
from __future__ import division
def Pythag(league):
def win_percentages():
for team, (runs_scored, runs_allowed) in league.iteritems():
win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
yield win_percentage
for win_percentage in win_percentages():
print win_percentage
Run Code Online (Sandbox Code Playgroud)