2017-12-12 1 views
0

나는 아래 그림과 같이 목록이 : 세 개 이상의 동일한 URL에서이 있는지 내가 확인할 수있는 방법, 파이썬

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']

을 이 목록? 나는 set() 기능을 시도했지만 중복 된 URL이있을 때마다 표시됩니다. 이것은 내가 뭘하려 :

if len(set(a)) < len(a): 

답변

2

당신은 세 번 이상 발생하는 URL의 수를 얻을 수 list.count를 사용할 수 있습니다

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 
+1

이 코드는'O (n^2)'시간에 실행되므로'[1, 1, 2, 2]'에 대해 잘못된 답을 줄 것입니다. –

7

사용 Counter.most_common :

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

이 가장 일반적인 요소가 나타나는 횟수를 반환합니다.

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'] 

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) 
0

목록에 3 번 이상 나타나는 URL이 있는지 확인하고 싶다고 가정합니다. 목록을 살펴보고 문자열을 키로 포함하는 사전을 만들고 값으로 각각의 개수를 입력 할 수 있습니다 (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