Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered tally of the cumulative number of unique words seen by a given position

Tags:

python

list

I have a list of words given below (example):

['the', 'counter', 'starts', 'the', 'starts', 'for']

I want to process this list in order and generate a pair (x,y) where x is incremented with each word and y is incremented only when it sees a unique word. So for the given example, my output should be like:
[(1,1) (2,2), (3,3) (4,3) (5,3) (6,4)]

I am not sure about how to do this in python. It would be great if i can get some insights on how to do this. Thanks.

like image 355
gsb Avatar asked Nov 27 '22 18:11

gsb


1 Answers

try this:

>>>from collections import Counter
>>>data = ['the', 'counter', 'starts', 'the', 'starts', 'for']
>>>tally=Counter()
>>>for elem in data:
>>>    tally[elem] += 1
>>>tally
Counter({'starts': 2, 'the': 2, 'counter': 1, 'for': 1})

from here: http://docs.python.org/2/library/collections.html

Of course, this results in a dictionary not a list. I wouldn't know if there's any way to convert this dict to a list (like some zip function ?) Hope it might be any help for anyone

like image 141
oneindelijk Avatar answered Mar 16 '23 00:03

oneindelijk