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.
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.
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.
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.
To determine how many items a set has, use the len() method.
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
.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With