Say i have a list x and : 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
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)
CodePudding user response:
Look at 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})
CodePudding user response:
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)
CodePudding user response:
Here's a quick solution without 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)])