如何在python列表中搜索几个元素?

时间:2019-05-14 13:06:35

标签: python list

我想编写一个程序来查找[a,b,c]中有多少[a,a, b,c,d,a,a,b,c,c,d,d,d]

我想要的答案是2。

列表中有四个a's,但是b是2,而c是3。 所以我想获得最少数量的[a,b,c]

7 个答案:

答案 0 :(得分:5)

这是一种方法:

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的切片或 window seq进行比较,如果相等,则返回1。因此,这将产生以下切片:

[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

答案 1 :(得分:3)

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

答案 2 :(得分:3)

您也可以使用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

答案 3 :(得分:0)

您也可以尝试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

答案 4 :(得分:0)

主要是一个字典,以保持每个字符出现的频率

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)

答案 5 :(得分:0)

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]))

答案 6 :(得分:0)

那是一种简单的方法: abc = ['a','a','b','c','d','a','a','b','c','c','d','d' ,'d'] min([['a','b','c']中i的[abc.count(i)))