gpt4 book ai didi

python - 如何获取多个字典中具有最高值的每个键的字典名称

转载 作者:行者123 更新时间:2023-11-30 23:08:28 25 4
gpt4 key购买 nike

我有一个名为 AllNames 的唯一名称列表和几个子列表,其中这些名称可以重复,或者根本找不到。例如

AllNames = ['John', 'Mark', 'Tony', 'Bob', 'Jack']

blue = ['John', 'John', 'Mark', 'Jack']
green = ['Mark', 'Mark', 'Jack']
red = ['Bob', 'Jack']
# These are dictionaries with the counts for each list
blueCounter = Counter({'John': 2, 'Mark': 1, 'Jack': 1})
greenCounter = Counter({'Mark': 2, 'Jack': 1})
redCounter = Counter({'Bob': 1, 'Jack': 1})

对于 AllNames 中的每个 name,我想获取 name 计数最高的列表名称,并将其放入新列表。基于以上,我会得到:

blueList = ['John'] # since John has the highest count across all lists
greenList = ['Mark']
redList =['Bob']

请注意,对于 'Jack',在所有三个列表中出现的次数相同,我不希望他的名字出现在任何地方。同样,'Tony' 的名字未出现在任何列表中,因此不应包含在内。

我正在尝试应用stats.iteritems,但这在一个字典中获得了最高值。

编辑:另一个例子

a=['John', 'John', 'John', 'Mark', 'Mark', 'Mark', 'Joe']
b= ['John', 'Mark', 'Joe', 'Joe', 'Joe', 'Jack']
c= ['Mark', 'Joe', 'Jack', 'Jack', 'Tony']

ac = Counter(a)
bc = Counter(b)
cc = Counter(c)

# >>> ac
# Counter({'John': 3, 'Mark': 3, 'Joe': 1})
# >>> bc
# Counter({'Joe': 3, 'Jack': 1, 'John': 1, 'Mark': 1})
# >>> cc
# Counter({'Jack': 2, 'Tony': 1, 'Joe': 1, 'Mark': 1})

结果应该是:

alist = ['John', 'Mark']
blist = ['Joe']
clist = ['Jack', 'Tony']

最佳答案

像这样:

from collections import Counter

AllNames = ['John', 'Mark', 'Tony', 'Bob', 'Jack']

blue = ['John', 'John', 'Mark', 'Jack']
green = ['Mark', 'Mark', 'Jack']
red = ['Bob', 'Jack']

# These are dictionaries with the counts for each list
blueCounter = Counter({'John': 2, 'Mark': 1, 'Jack': 1})
greenCounter = Counter({'Mark': 2, 'Jack': 1})
redCounter = Counter({'Bob': 1, 'Jack': 1})

names = []
for counter in blueCounter, greenCounter, redCounter:
name_with_highest_count = counter.most_common()[0][0]
if name_with_highest_count in AllNames:
names.append([name_with_highest_count])

blueList, greenList, redList = names

print(blueList) # -> ['John']
print(greenList) # -> ['Mark']
print(redList) # -> ['Bob']

关于python - 如何获取多个字典中具有最高值的每个键的字典名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com