简体   繁体   中英

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

In my code, I want to check whether I could check if a certain string eg

a="."

repeats more than once in a list. eg

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

how would I do that?

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

Use count function.

您可以使用内置的count方法

n_occurences = b.count(a)

Use collections.Counter() or simply list.count()

list.count(x) will return the count of x in list

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

collections.Counter will return a dictionary, which have count information of every item in a list:

from collections import Counter

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

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

Use count function.

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

Using collections.Counter :

from collections import Counter

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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