Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a list:

originalList = ['Item1', 'Item1', 'Item1', 'Item2', 'Item2', 'Item3', 'Item4']

I need to create two lists based off of the originalList

The first list I need, should list all unique items, such as:

['Item1', 'Item2', 'Item3', 'Item4']

While the other should list the count of each unique value:

[3, 2, 1, 1]

Please help


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use Counter in the following way:

from collections import Counter
res = dict(Counter(originalList))

And getting the keys will give the resulted list and the values will be the count of each element.

To get the 2 lists:

keys, values = map(list, zip(*d.items()))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...