[英]How do i make python find differing elements in a list and their number of occurrences within it
假設我有一個列表 x 並且: x = ['a', 'b', 'c', 'c', 'c', 'c', 'a']
如果用戶或其他程序員不知道列表中的元素,我如何告訴 python 找到唯一元素所以如果他們問(此列表中有什么?) python 將Z78E6221F6393D1356681DB398F134CED6元素: a、b和c
如果用戶詢問(每個有多少)python 應該是 output:即 - (在此列表中,有4個c b實例和2個實例)
x = ['a', 'b', 'c', 'c', 'c', 'c', 'a']
counter = collections.Counter(x)
print(len(counter)) # 3
print(counter) # Counter({'c': 4, 'a': 2, 'b': 1})
我提議:
ItemList = ['a', 'b', 'c', 'C', 'c', 'C', 'A']
NewDict = {}
for Item in ItemList:
if Item not in NewDict:
NewDict[Item] = 0
NewDict[Item] += 1
print(NewDict)
如果你不想尊重這個案子:
ItemList = ['a', 'b', 'c', 'C', 'c', 'C', 'A']
NewDict = {}
for Item in ItemList:
if Item.lower() not in NewDict:
NewDict[Item.lower()] = 0
NewDict[Item.lower()] += 1
print(NewDict)
這是沒有collections.Counter
的快速解決方案:
x = ['a', 'b', 'c', 'c', 'c', 'c', 'a']
print(len(set(x)))
print([f"{i} - {x.count(i)}" for i in set(x)])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.