簡體   English   中英

我如何讓 python 在列表中找到不同的元素及其在其中的出現次數

[英]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、bc

如果用戶詢問(每個有多少)python 應該是 output:即 - (在此列表中,有4c b實例和2實例)

查看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})

我提議:

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.

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