我有一个具有以下结构的字典:
d = dict()
d[1] = [["car", 100, 23, 35], ["car", 101, 55, 67], ["bus", 111, 98, 99]]
d[2] = [["bus", xxx, xx, xx], ["car", 101, xx, xx], ["bus", xxx, xx, xx]]
...
现在我要做的是将每个键的值的第一个元素更改为该键的多数类。例如,对于键为 1 的项目,多数类是“汽车”,因为它出现了两次,而“公共(public)汽车”只出现了一次。
对于键 2,多数类是“总线”。所以,在后期处理之后,字典应该是这样的:
d[1] = [["car", 100, 23, 35], ["car", 101, 55, 67], ["car", 111, 98, 99]]
d[2] = [["bus", xxx, xx, xx], ["bus", 101, xx, xx], ["bus", xxx, xx, xx]]
是否有一些 pythonic 方法可以做到这一点?我正在考虑遍历所有键的所有值,收集列表中的值,找到最大出现次数,然后再次迭代并更新值,但这看起来有点难看。
想知道是否有一种简洁的表达方式?
最佳答案
使用 collections.Counter
:
>>> from collections import Counter
>>> for key, values in d.items():
... counter = Counter(value[0] for value in values)
... majority = counter.most_common(1)[0]
... for value in values:
... value[0] = majority
关于python根据多数更改字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67749053/