Skip to main content
 首页 » 编程设计

python之一个术语出现在多少个列表中

2025年05月04日22TianFang

我有 X 个列表,例如:

[potato, pie] 
[chicken,chicken,pie,donkey,potato,potato] 

我想检查一个词出现在多少个列表中:

例如:

对于上面的两个列表,我希望输出是:

(potato,2) 
(pie,2) 
(chicken,1) - chicken is only one because it appears only in list two, not in list one. 
(donkey,1) 

我的尝试,但我做的完全错误并且感到困惑,如果我什至采取了正确的方法:

x = ['potato', 'pie'] 
z = ['chicken','chicken','pie','donkey','potato','potato'] 
list_final = x + z 
 
dict_final = {} 
 
for item in list_final: 
    if item in dict_final.keys(): 
        dict_final.update({item:(dict_final.get(item) + 1)}) 
    else: 
        dict_final.update({item:1}) 
 
 
print(dict_final) 

我试过了,但这只计算它出现在列表中的所有次数:

{'potato': 3, 'pie': 2, 'chicken': 2, 'donkey': 1} 

但我想得到:

{'potato': 2, 'pie': 2, 'chicken': 1, 'donkey': 1} 

请您参考如下方法:

如果你让它更实用)

 
from collections import Counter 
from functools import reduce 
 
x = ['potato', 'pie'] 
y = ['chicken','chicken','pie','donkey','potato','potato'] 
all_lists = [x, y] 
dict(Counter(reduce(lambda x, y: x + list(set(y)), all_lists, [])).most_common()) 
# {'potato': 2, 'pie': 2, 'donkey': 1, 'chicken': 1}