Posted on • Originally published atflaviabastos.ca on
Map a string in Python with enumerate
Problem: create a map of the letters and indices in a string.
My first approach was to loop over the string usingrange(len(s)), and checking if the letter exists in the map before adding it:
s = 'mozzarella' mapped_s = {} for i in range(len(s)): if s[i] in mapped_s: mapped_s[s[i]].append(i) else: mapped_s[s[i]] = [i] print(f' mapped: {mapped_s}')
That works:
{'m': [0], 'o': [1], 'z': [2, 3], 'a': [4, 9], 'r': [5], 'e': [6], 'l': [7, 8]}
but there’s a more pythonic way of getting this map: use enumerate()!
letters = 'mozzarella' mapped_s = collections.defaultdict(list) for index, letter in enumerate(letters): mapped_s[letter].append(index) print(f'mapped: {dict(mapped_s)}')
Enumerate is apython built-in function that gives you a list of tuples of the indices and the elements in an iterable:
print(f'enum {list(enumerate('mozzarella'))}')enum [(0, 'm'), (1, 'o'), (2, 'z'), (3, 'z'), (4, 'a'), (5, 'r'), (6, 'e'), (7, 'l'), (8, 'l'), (9, 'a')]
It can be used to loop over the iterable while keeping track of the index and the element similar to what _range(len(s)) _was doing in my first example:
for i, element in enumerate('mozzarella'): print(f'{i}: {element}')
It also removes the need to check if the letter already exists before creating that letter’s map!
You can read more about enumeratein the docs or this super nice article byDan Bader.
The postMap a string in Python with enumerate was originally published onflaviabastos.ca
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse