簡體   English   中英

如何確定列表中是否有任何值超過兩次?

[英]How to determine if any value occurs more than twice in a list?

我有一個列表,並想確定是否有任何值出現兩次以上。 我已經嘗試過使用集合和計數器,但我無法將它們評估為單個True或False值。

myArray=[1,1,1,1,1,1,1,1,2]

我希望它返回:如果任何值出現超過兩次,則為True

任何幫助都表示贊賞,如果解決方案很快就會有所幫助。 我正在檢查數十萬個列表。 我是編程新手,這是我的第一篇文章。

編輯:我的嘗試,我也是stackoverflow UI的新手

import collections

arr= [1,2,3,5,6]

Counter(arr)

返回: Counter({1: 1, 2: 1, 3: 1, 5: 1, 6: 1})

您可以使用collections.Counter

from collections import Counter
print any(count > 2 for count in Counter(myArray).itervalues())   # True

或者,如果您使用的是Python 3:

from collections import Counter
print(any(count > 2 for count in Counter(myArray).values()))   # True

您始終可以構造值的直方圖,並查看是否有任何條目大於2。 它可能看起來像這樣:

def is_more_than_twice(l):
   hist = {}
   for el in l:
       if el in hist:
           hist[el] += 1
       else:
           hist[el] = 1
       if hist[el] > 2:
           return True
   return False

您不需要迭代直到列表的末尾,直到您遇到看到元素el出現兩次以上的情況。

這是使用collections.defaultdict的一種方法。 與@ HoriaComan的方法一樣,此解決方案不需要迭代整個列表。

myArray = [1,1,1,1,1,1,1,1,2]

from collections import defaultdict

def count_limit(L, k=2):
    d = defaultdict(int)
    for item in L:
        if d[item] == k:
            return True
        else:
            d[item] += 1
    return False

res = count_limit(myArray)  # False

績效基准

為了證明這種影響,我們可以在更大的迭代Counter上與Counter進行比較:

myArray = [1,1,1,1,1,1,1,1,2]*10000

from collections import defaultdict, Counter

def count_limit(L, k=2):
    d = defaultdict(int)
    for item in L:
        if d[item] == k:
            return True
        else:
            d[item] += 1
    return False

def count_limit_counter(myArray):
    return any(count > 2 for count in Counter(myArray).values())

%timeit count_limit(myArray)          # 1.52 µs per loop
%timeit count_limit_counter(myArray)  # 6.64 ms per loop

嘗試使用set()

def OccursMoreThanTwice(myArray):
    for e in myArray:
        if myArray.count(e) > 2:
           return True
    return False

print OccursMoreThanTwice([1,1,1,1,1,1,1,1,2])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM