假設我有一個串列 x 和: x = ['a', 'b', 'c', 'c', 'c', 'c', 'a']
如果用戶或其他程式員不知道串列中的元素,我如何告訴 python 找到唯一元素所以如果他們問(這個串列中有什么?)python 會輸出:在這個串列中有3 個不同的元素元素:a、b和c
如果用戶詢問(每個有多少)python 應該輸出:即 - (在此串列中,有4個c實體,2個a實體和1個b實體)
uj5u.com熱心網友回復:
看看collections.Counter。
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})
uj5u.com熱心網友回復:
我提議:
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)
uj5u.com熱心網友回復:
這是一個沒有的快速解決方案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)])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368267.html
