[英]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.