如何检查列表中是否有3个以上相同的字符串,Python

2024-06-01 01:14:42 发布

您现在位置: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):

Tags: 函数orgcomurl列表netlenwww
3条回答

使用Counter.most_common

>>> Counter(a).most_common(1)[0][1]
4

返回最常用元素出现的次数。你知道吗

您可以使用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)

可以使用list.count获取出现三次或三次以上的URL数:

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

相关问题 更多 >