[英]How to check if there are more than 3 identical string in a list, Python
[英]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)
将返回list
中x
的计数
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.