如何计算python列表中字符串列表的出现次数?

时间:2018-09-29 22:50:50

标签: python python-3.x

例如,我的列表是

lst=['hello','world','this','is','hello','world','world','hello']
subString=['hello','world']

在这种情况下,我要查找的结果是2,因为列表['hello','world']以相同的顺序出现了两次。

我尝试做

list(filter(lambda x : x in substring,lst))

但这会返回所有的问候和世界

4 个答案:

答案 0 :(得分:0)

您可以将元素加入列表列表,然后按与您的子字符串数组匹配的元素进行过滤。


joinedWords = [lst[n:n + len(subString)] for n in range(0, len(lst), len(subString))]
    # => [['hello', 'world'], ['this', 'is'], ['hello', 'world'], ['world', 'hello']]
filtered = list(filter(lambda x: x == subString, joinedWords))

print(len(filtered))  # 2

答案 1 :(得分:0)

您可以在两个列表上使用" ".join()创建一个字符串,然后使用str.count()计算subStringlst的出现次数

lst=['hello','world','this','is','hello','world','world','hello']
subString=['hello','world']

l = " ".join(lst)
s = " ".join(subString)

count = l.count(s)
print("Joined list:", l)
print("Joined substring:", s)
print("occurrences:", count)

输出:

Joined list: hello world this is hello world world hello
Joined substring: hello world
occurrences: 2

答案 2 :(得分:0)

由于在这种情况下所有元素都是字符串,所以我将从每个列表中创建一个字符串,然后计算第一个字符串中第二个字符串的出现次数:

lst=['hello','world','this','is','hello','world','world','hello']
subString = ['hello','world']

s = ' '.join(lst)
subs = ' '.join(subString)

print(s.count(subs))

答案 3 :(得分:0)

使用this answerwindow中的Counter生成器,可以表示为:

from collections import Counter

lst=['hello','world','this','is','hello','world','world','hello']
subString=('hello','world')

counts = Counter(window(lst, len(subString)))

print(counts[subString])
# 2

如果您想跳过Counter,可以这样做

print(sum(x == subString for x in window(lst, len(subString))))