list - 在python列表中,如何搜索多个元素?

我想写一个程序来找出[a,a, b,c,d,a,a,b,c,c,d,d,d]中的[a,b,c]数量。

我想要的答案是2.

列表中有四个,,但是b是2,c是3,所以,我想得到[a,b,c]的最小数量

时间:

以下是一种方法:


l = ['a','b','c','d','a','a','b','c','c','d','d','d']


seq = ['a','b','c']



sum(1 for i in range(len(l) - len(seq)-1) if l[i: i + len(seq)] == seq)


# 2



在每次迭代中,我们将l的一块或窗口与seq进行比较,如果它们相等,则返回1 ,因此,这将产生以下slice:


[l[i: i + len(seq)] for i in range(len(l) - len(seq)-1)]



[['a', 'b', 'c'],


 ['b', 'c', 'd'],


 ['c', 'd', 'a'],


 ['d', 'a', 'a'],


 ['a', 'a', 'b'],


 ['a', 'b', 'c'],


 ['b', 'c', 'c'],


 ['c', 'c', 'd']]



或者我们也可以使用join将两个列表转换为字符串,然后使用str.count


''.join(l).count(''.join(seq))


# 2




abc = ['a', 'a', 'b', 'c', 'd', 'a', 'a', 'b', 'c', 'c', 'd', 'd', 'd']


min([abc.count(i) for i in ['a', 'b', 'c']])



你也可以使用collections.Counter。

这个想法是计算列表中所有元素的计数并采取最小的键a,b,c计数。


from collections import Counter


l = ['a','b','c','d','a','a','b','c','c','d','d','d']


seq = ['a','b','c']



#Create counter of list


c = Counter(l)


#{'d': 4, 'a': 3, 'c': 3, 'b': 2}


#Take minimum count from counts of keys a,b and c


result = min([c[key] for key in seq])


print(result)



结果将是2

你也可以尝试Counter


>>> from collections import Counter


>>> 


>>> l = ['a','b','c','d','a','a','b','c','c','d','d','d']


>>> counter = Counter(l)


>>> 


>>> min(counter['a'], counter['b'], counter['c'])


2



保留每个字符出现频率的主词典


from collections import defaultdict


dic=defaultdict(int)


l=[a,a, b,c,d,a,a,b,c,c,d,d,d]


seq=[a,b,c]



for i in l:


 dic[i]+=1



sol = min([dic[i] for i in seq])



print(sol)



c = ['a','b','c'] cc = ['a','a','b','c','d','a','a','b','c','c','d','d','d']


result = {}


for i in c:


 res = cc.count(i)


 chec_res = {i:res}


 result.update(chec_res)



Min_val = min(result.keys(), key=(lambda m: result[m]))



这样做是一种简单的方法: abc = ['a','a','b','c','d','a','a','b','c','c','d','d','d'] min( [abc.count(i) for i in ['a','b','c'] ] )

...