我有以下词典列表。

  player = [{"Cate": "EU91", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU91", "Points": 216, "Good": 1,  },
            {"Cate": "EU95", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU99", "Points": 216, "Good": 1,  }]


在上面的字典中,我想基于等于“ EU91”或“ FU91”的“类别”值将特定的字典存储到某个变量中。我试过的是:

if any(d['Cate'] == 'EU91' or d['Cate'] == 'FU91'  for d in player):
     print('U91 category exists')


在上面的代码中,我仅检查是否存在EU91或FU91。我需要在某些变量中存储特定的词典(“ Cate”值等于EU91或FU91),并更新选定的词典,如下所示:

list = [ {"Cate": "U91", "Points_A": 256, "good": 1 }, {"Cate": "U91","Points_B": 256, "good": 1 } ]


说明:如果同时存在EU91和FU91,则将特定的“ Cate”字典更新为“ U91”,然后将EU91的“ Points”更新为“ Points_A”,对于FU91的“ Points”更新为“ Points_B”。

我期待结果:

var = [{"Cate": "U91", "Points_A": 256, "good": 1 },{"Cate": "U91","Points_B": 256, "good": 1}]


希望大家都理解我的问题。
有任何想法吗?

最佳答案

在条件条件下使用简单的for循环。

例如

player = [{"Cate": "EU91", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU91", "Points": 216, "Good": 1,  },
            {"Cate": "EU95", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU99", "Points": 216, "Good": 1,  }]
result = []
for x in player:
    if x['Cate'] == 'EU91':
        x['Points_A'] = x.pop('Points')
    elif  x['Cate'] == 'FU91':
        x['Points_B'] = x.pop('Points')

    if "Points_A" in x or "Points_B" in x:
        x['Cate'] = "U91"
        result.append(x)

print(result)


O / P:

[{'Cate': 'U91', 'good': 1, 'Points_A': 256}, {'Cate': 'U91', 'Good': 1,
 'Points_B': 216}]

关于python - 从“词典”列表中选择“词典”并进行一些更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58760379/

10-13 05:46