简体   繁体   English

我如何让 python 在列表中找到不同的元素及其在其中的出现次数

[英]How do i make python find differing elements in a list and their number of occurrences within it

Say i have a list x and: x = ['a', 'b', 'c', 'c', 'c', 'c', 'a']假设我有一个列表 x 并且: x = ['a', 'b', 'c', 'c', 'c', 'c', 'a']

if a user, or another programmer, does not know the elements in a list, how do I tell python to find the unique elements So if they ask (what is in this list?) python would output: in this list there are 3 different elements: a, b and c如果用户或其他程序员不知道列表中的元素,我如何告诉 python 找到唯一元素所以如果他们问(此列表中有什么?) python 将Z78E6221F6393D1356681DB398F134CED6元素: a、bc

and if the user asks (how many of each) python should output: ie - (in this list, there are 4 instances of c , 2 instances of a and 1 instance of b )如果用户询问(每个有多少)python 应该是 output:即 - (在此列表中,有4c b实例和2实例)

Look at collections.Counter .查看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})

I propose:我提议:

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)

And if you don't want respect the case:如果你不想尊重这个案子:

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)

Here's a quick solution without collections.Counter :这是没有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