繁体   English   中英

如何检查某个字符串是否在列表中重复多次

[英]How to check if a certain string repeats more than once in a list

在我的代码中,我想检查是否可以检查某个字符串,例如

a="."

在列表中重复多次。 例如

b=[".", ".", "Hello world"]

我该怎么办?

b=[".", ".", "Hello world"]
print(b.count(a))
>>> 2

使用count功能。

您可以使用内置的count方法

n_occurences = b.count(a)

使用collections.Counter()或简单地使用list.count()

list.count(x)将返回listx的计数

b=[".", ".", "Hello world"]
# Check for "."
print(b.count(".")

collections.Counter将返回一个字典,该字典具有列表中每个项目的count信息:

from collections import Counter

b=[".", ".", "Hello world"]
# Check for "."
count = b.Counter() 

if count["."] > 1:
   print("More than one occurance")

使用计数功能。

    a="."
    b=[".", ".", "Hello world"]
    if b.count(a) > 1:
        print("more than 1 time")

使用collections.Counter

from collections import Counter

a = "."
b=[".", ".", "Hello world"]

print(Counter(b)[a]) # 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM