首页 > 解决方案 > 通过循环比较列表中的嵌套字典值?

问题描述

我有一个程序可以抓取一些统计数据并计算一些球队在一个篮球赛季中的 ELO。当我尝试计算每个团队的预期获胜百分比时,问题仍然存在,但这些值都存储在同一个嵌套字典列表中:eList=[{'Perth': 1715}, {'Melbourne': 1683}, {'Phoenix': 1648}, {'Sydney': 1605}, {'The Hawks': 1573}, {'Brisbane': 1573}, {'Adelaide': 1523}, {'New Zealand': 1520}, {'Cairns': 1477}]. 我试过嵌套 for 循环一次迭代两个值,但会导致错误。我正在尝试遍历列表字典中各个团队的所有 ELO 值,然后将它们相互交叉比较,以便可以将值输入到我的其他函数和结果输出中:

def expected_result(rating1, rating2):
    exp = (rating2 - rating1)/400.
    Ea = 1/(1 + math.pow(10, exp))
    Eb = 1/(1 + math.pow(10, -exp))
    return Ea*100, Eb*100

标签: pythonlistdictionarynestedlogic

解决方案


import math
eList=[{'Perth': 1715}, {'Melbourne': 1683}, {'Phoenix': 1648}, {'Sydney': 1605}, {'The Hawks': 1573}, {'Brisbane': 1573}, {'Adelaide': 1523}, {'New Zealand': 1520}, {'Cairns': 1477}]
val=[list(i.values())[0] for  i in eList]
#extracting just the values from eList

from itertools import combinations
g=list(combinations(val, 2))
#pairing up two teams values
def expected_result(rating1, rating2):
    exp = (rating2 - rating1)/400.
    Ea = 1/(1 + math.pow(10, exp))
    Eb = 1/(1 + math.pow(10, -exp))
    return Ea*100, Eb*100

for i in g:
    print(expected_result(*i))
    #unpacking each tuple into function

首先,一旦我们有了可以使用for循环解包的元组列表,我们需要在不重复的情况下对每个团队进行配对输出:

(54.592192278048365, 45.407807721951635)
(59.52430396515719, 40.47569603484281)
(65.32171672188699, 34.67828327811303)
(69.36879164219654, 30.63120835780346)
(69.36879164219654, 30.63120835780346)......

推荐阅读