迭代Python中List对应的字典键值 [英] Iterating Over Dictionary Key Values Corresponding to List in Python

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

问题描述

使用 Python 2.7.我有一个字典,以团队名称为键,以每个团队的得分和允许的运行次数作为值列表:

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).

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

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

感谢您的帮助.

推荐答案

您有多种迭代字典的选项.

You have several options for iterating over a dictionary.

如果你迭代字典本身(for team in League),你将迭代字典的键.使用 for 循环进行循环时,无论是遍历 dict (league) 本身还是 league.keys():

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, or league.keys():

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

您还可以通过迭代 league.items() 来同时迭代键和值:

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

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

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

You can even perform your tuple unpacking while iterating:

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

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

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