Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List elements’ counter

New to Python here.

I am looking for a simple way of creating a list (Output), which returns the count of the elements of another objective list (MyList) while preserving the indexing(?).

This is what I would like to get:

MyList = ["a", "b", "c", "c", "a", "c"]
Output = [ 2 ,  1 ,  3 ,  3 ,  2 ,  3 ]

I found solutions to a similar problem. Count the number of occurrences for each element in a list.

In  : Counter(MyList)
Out : Counter({'a': 2, 'b': 1, 'c': 3})

This, however, returns a Counter object which doesn't preserve the indexing.

I assume that given the keys in the Counter I could construct my desired output, however I am not sure how to proceed.

Extra info, I have pandas imported in my script and MyList is actually a column in a pandas dataframe.

like image 904
CAPSLOCK Avatar asked Feb 18 '19 14:02

CAPSLOCK


People also ask

How do you count elements in a list?

Using Len() function to Get the Number of Elements We can use the len( ) function to return the number of elements present in the list.

How do you count items in a list in Python?

There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.

How do I turn a list into a counter in Python?

In Python, you can count the total number of elements in a list or tuple with the built-in function len() and the number of occurrences of an element with the count() method.

How do you count elements in a set Python?

To determine how many items a set has, use the len() method.


2 Answers

Instead of listcomp as in another solution you can use the function itemgetter:

from collections import Counter
from operator import itemgetter

lst = ["a", "b", "c", "c", "a", "c"]

c = Counter(lst)
itemgetter(*lst)(c)
# (2, 1, 3, 3, 2, 3)

UPDATE: As @ALollz mentioned in the comments this solution seems to be the fastet one. If OP needs a list instead of a tuple the result must be converted wih list.

like image 75
Mykola Zotko Avatar answered Oct 14 '22 10:10

Mykola Zotko


You can use the list.count method, which will count the amount of times each string takes place in MyList. You can generate a new list with the counts by using a list comprehension:

MyList = ["a", "b", "c", "c", "a", "c"]

[MyList.count(i) for i in MyList]
# [2, 1, 3, 3, 2, 3]
like image 20
yatu Avatar answered Oct 14 '22 09:10

yatu