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