Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Thursday, May 3, 2012

Using enumerate to retrieve item and index in iterable

This article shows how you can use enumerate to extract letters from a word and group all letters and calculate a list of indexes where they are used.
#Goal: Build a map of indexes for all tokens in the string
from collections import defaultdict 

text = 'robby pelssers'
d = defaultdict(list)
for index, letter in ((index, letter) for index, letter in enumerate(text)):

for item in d.items():
    print item

(' ', [5])
('b', [2, 3])
('e', [7, 11])
('l', [8])
('o', [1])
('p', [6])
('s', [9, 10, 13])
('r', [0, 12])
('y', [4])

No comments:

Post a Comment