簡體   English   中英

計算列表中元素的出現次數

[英]Count occurrences of an element in list

我知道關於這個特定主題已經有很多問題,但我找不到適合我問題的解決方案。

我有輸入:

2, 20, 15, 16, 17, 3, 8, 10, 7

我想看看我的代碼中是否有“雙重”數字。 我試過使用這段代碼。

lijst = input('Give a list:  ')
teller = 0
for i in lijst.split(','):
    if lijst.count(i) != 1:
        teller += 1
print(teller != 0)

通常我應該得到False,因為給定列表中沒有雙數字。 但是,我接受了True。 我建議這是因為2也出現在20。

True

有誰知道如何避免這個問題,所以'2'不計算兩次?

您可以使用collections.Counter來完成它

>>> data = [2, 20, 15, 16, 17, 3, 8, 10, 7]
>>> from collections import Counter
>>> Counter(data)
Counter({2: 1, 3: 1, 7: 1, 8: 1, 10: 1, 15: 1, 16: 1, 17: 1, 20: 1})
>>> 

它計算出現次數並返回帶有鍵的dict表示項目,值是出現的次數。

如果您只需要知道是否有重復項,無論哪個項目是重復項,您只需在列表上使用Set並在之后檢查len()

len(data) == len(set(data))

您可以將輸入的長度與輸入中唯一元素集的長度進行比較:

def has_repeated_elements(input):
    """returns True if input has repeated elements,
    False otherwise"""
    return len(set(input)) != len(input)

print(not has_repeated_elements(input))

暫無
暫無

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

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