[英]How to check if there are more than 3 identical string in a list, Python
我有一個列表,如下所示:
a = ['www.hughes-family.org', 'www.bondedsender.com', 'thinkgeek.com', 'www.hughes-family.org', 'www.hughes-family.org', 'lists.sourceforge.net', 'www.hughes-family.org']
如何檢查此列表中是否有三個以上相同的URL? 我已經嘗試過set()
函數,但是只要有重復的url,它就會顯示出來。 這是我嘗試的:
if len(set(a)) < len(a):
使用Counter.most_common
:
>>> Counter(a).most_common(1)[0][1]
4
這將返回最常見元素出現的次數。
您可以使用list.count
獲取出現3次或以上的網址數量:
urls = ['www.hughes-family.org', 'www.bondedsender.com', 'thinkgeek.com', 'www.hughes-family.org', 'www.hughes-family.org', 'lists.sourceforge.net', 'www.hughes-family.org']
new_urls = [url for url in urls if urls.count(url) > 1]
if len(new_urls) > 3:
pass #condition met
您可以使用dict來捕獲重復的內容:
a = ['www.hughes-family.org', 'www.bondedsender.com', 'thinkgeek.com', 'www.hughes-family.org', 'www.hughes-family.org', 'lists.sourceforge.net', 'www.hughes-family.org']
count={}
for i,j in enumerate(a):
if j not in count:
count[j]=[i]
else:
count[j].append(i)
for i,j in count.items():
if len(j)>1:
#do you stuff
print(count)
輸出:
{'www.hughes-family.org': [0, 3, 4, 6], 'thinkgeek.com': [2], 'www.bondedsender.com': [1], 'lists.sourceforge.net': [5]}
您可以使用defaultdict的第二種方法:
import collections
d=collections.defaultdict(list)
for i,j in enumerate(a):
d[j].append(i)
print(d)
我假設您要檢查列表中是否有任何URL出現3次以上。 您可以瀏覽列表,並創建一個字典,其中包含字符串作為鍵,並將它們各自的計數作為值(類似於collections.Counter的輸出)。
In [1]: a = ['www.hughes-family.org', 'www.bondedsender.com', 'thinkgeek.com', '
...: www.hughes-family.org', 'www.hughes-family.org', 'lists.sourceforge.net'
...: , 'www.hughes-family.org']
In [2]: is_present = False
In [3]: url_counts = dict()
In [4]: for url in a:
...: if not url_counts.get(url, None): # If the URL is not present as a key, insert the URL with value 0
...: url_counts[url] = 0
...: url_counts[url] += 1 # Increment count
...: if url_counts[url] > 3: # Check if the URL occurs more than three times
...: print "The URL ", url, " occurs more than three times!"
...: is_present = True
...: break # Come out of the loop if any one of the URLs occur more than three times
# output - The URL www.hughes-family.org occurs more than three times!
In [5]: is_present # To check if there is a URL which occurs more than three times
Out[5]: True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.