List python 2.7中列表之间公共元素的频率
我有两份清单:List python 2.7中列表之间公共元素的频率,list,python-2.7,duplicates,frequency,List,Python 2.7,Duplicates,Frequency,我有两份清单: list1 = ['red','blue', 'yellow'] #unique list2 = ['green','purple','red','yellow','purple', 'red'] #duplicates ['red', 2],['blue',0],['yellow',1] 我找到了多个Q&A,用于查找两个列表之间的唯一公共元素或列表中元素的频率: import numpy as np match = np.in1d(list1,list2, assum
list1 = ['red','blue', 'yellow'] #unique
list2 = ['green','purple','red','yellow','purple', 'red'] #duplicates
['red', 2],['blue',0],['yellow',1]
我找到了多个Q&A,用于查找两个列表之间的唯一公共元素或列表中元素的频率:
import numpy as np
match = np.in1d(list1,list2, assume_unique=False)
match = list(set(list1).intersection(set(list2)))
match = set(list1) & set(list2)
[element for element in list1 if element in list2]
list2, common = list1[:], [ e for e in list1 if e in list2 and (list2.pop(list2.index(e)))]
from scipy.stats import itemfreq
count = itemfreq(res)
list.count
但我需要的是两个列表之间公共元素(如果有)的频率:
list1 = ['red','blue', 'yellow'] #unique
list2 = ['green','purple','red','yellow','purple', 'red'] #duplicates
['red', 2],['blue',0],['yellow',1]
一些理解可以简明扼要地做到这一点:
list1 = [1,2,3]
list2 = [3,4,5,3,3]
itemcounter = {item:count for item, count in [(item, list2.count(item)) for item in set(list1)]}
final_counts = [(item, count) for item, count in itemcounter.iteritems()]
print(final_counts)
…产生了以下结果:
[(1, 0), (2, 0), (3, 3)]
Python 2.7有一个计数器类,可用于:
from collections import Counter
list1 = ['red', 'blue', 'yellow']
list2 = ['green', 'purple', 'red', 'yellow', 'red']
set_list1 = set(list1)
list2_in_list1 = [x for x in list2 if x in set_list1]
count = Counter(list2_in_list1)
print count
# gives: Counter({'red': 2, 'yellow': 1})
将列表1转换为集合是出于性能原因(检查集合中的项目比检查列表快);对于短列表,您可以跳过它。您可以使用列表中可用的count语句
list1 = ['red','blue', 'yellow']
list2 = ['green','purple','red','yellow','purple', 'red']
for color in list1:
count = list2.count(color)
print [color, count],
这将打印出以下内容:
琼尼的的确更快,但斯科特的更简洁