-1

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

Llewellyn Hattingh
  • 306
  • 1
  • 5
  • 16

4 Answers4

3

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()))
David
  • 8,113
  • 2
  • 17
  • 36
  • This is great! However, I would need two lists and is new to python. How can I create the two lists based off of the newly created dictionary? – Llewellyn Hattingh Jan 05 '21 at 17:39
2
originalList = ['Item1', 'Item1', 'Item1', 'Item2', 'Item2', 'Item3', 'Item4']

unique = sorted(set(originalList))

frequency = [originalList.count(x) for x in unique]

print(unique)
print(frequency)

>>> [3, 2, 1, 1]
>>> ['Item1', 'Item2', 'Item3', 'Item4']

Use set to remove duplicates and sorted to order the list, this will give you the unique list

Then count the frequency of each unique item in the original list

coderoftheday
  • 1,987
  • 4
  • 7
  • 21
1

I agree that you can use Counter like David S mentioned, but if you're after the lists, you can call the list() constructor on the dict's .keys() and .values(). The complete code is something like:

from collections import Counter

counts = Counter(originalList)  # Counter is a subclass of dict

# for ['Item1', 'Item2', 'Item3', 'Item4']:
list_1 = list(counts.keys())

# for [3, 2, 1, 1]
list_2 = list(counts.values())
1

The way mentioned by Jordan Engstrom can fetch you your answer. Another way can be:

unique_list = sorted(list(set(originalList)))
count_list = []
for item in unique_list:
    count_list.append(original_list.count(item))

For less number of items in a list .count() should run faster than Counter. Why is Collections.counter so slow? You can read more about Counter's performance in this thread.

Aman Goel
  • 31
  • 3