簡體   English   中英

如何獲取列表中非重復值的計數

[英]How to get count of non-repeating values in list

我知道我可以執行以下操作來獲取列表中元素的出現次數:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

輸出:

['a', 'c', 'b']
[2, 1, 1]

但我想得到b c b c中只出現一次。 有沒有什么方法可以在不使用Counter甚至不使用Counter的上述輸出的情況下以簡潔/pythonic 的方式做到這一點?

你可以做一個算法來做到這一點,這是一個單行(感謝@db):

sum(x for x in Counter(words).values() if x == 1)

或多於一行:

seen = []
count = 0

for word in words:
  if word not in seen:
    count += 1
    seen.append(word)

使用集合結構。

unique_elements = set(['a', 'b', 'c', 'a']))
# results in: {'c', 'b', 'a'}

如果需要,將其轉換回列表很簡單:

list(set(['a', 'b', 'c', 'a'])
# results in: ['a', 'c', 'b']

暫無
暫無

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

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