firetheRookie firetheRookie - 1 year ago 63
Python Question

python - count that starts over when a value in list changes

I have the following list:

my_list=['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']

I want to create a new list which is used to count the sum of all occurrences of a unique value in my_list as my_list is iterated over. The iteration should start with the first item in my_list and go over all items in my_list.

For example, I want a list that looks like this:

[1, 2, 3, 4, 1, 2, 1, 2, 1]

Answer Source

You may use list.count() to find the occurence of word on the sliced list along with list comprehension:

>>> my_list= ['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']
>>> [my_list[:i].count(name) for i, name in enumerate(my_list, 1)]
[1, 2, 3, 4, 1, 2, 1, 2, 1]

Here, my_list[:i].count(name) will give the count of occurrence of name in my_list from 0th to ith index (excluding the value at ith index). To know about enumerate(), refer the document. I am passing start = 1 with enumerate which means value of i will start from 1.

Example related to slicing and count:

>>> my_list[:6]      # Values upto `5`th index
['John', 'John', 'John', 'John', 'Joe', 'Joe']  
>>> my_list[:6].count('John')   # occurence of `John` in the list
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download