Leandro Baruch
Leandro Baruch

Reputation: 117

How to SUM items in list separately?

I am trying to create a function that returns item types and the count items from a list.

I have:

def count_items(column_list):
    item_types = []
    count_items = []

    item_types = set(column_list)
    print(item_types)
    count_items = ????

    return item_types, count_items

The return fro item_types is:

{'', 'Female', 'Male'}

If I use len function to count_items, it will return the total of the three values, like {1500}, but I need them separately, like {150, 550, 800} What should I use?

Upvotes: 0

Views: 74

Answers (2)

Marcus.Aurelianus
Marcus.Aurelianus

Reputation: 1518

You can return the counts only with list comprehension and set,

def count_items(column_list):

    item_types = set(column_list)

    return [column_list.count(item) for item in item_types]

column_list=['male','male','','','','female','male','female']


print(count_items(column_list))

Output:

[3, 2, 3]

Or Both,

def count_items(column_list):

    item_types = set(column_list)

    return [[item,column_list.count(item)] for item in item_types]

Output:

[['', 3], ['male', 3], ['female', 2]]

Upvotes: 2

Reblochon Masque
Reblochon Masque

Reputation: 36662

You can use collections Counter:

from collections import Counter

my_list_of_items = ['a', 'a', 'b']

counter = Counter(my_list_of_items)

---> {'a': 2, 'b': 1}

Upvotes: 2

Related Questions