Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Flávia Bastos
Flávia Bastos

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Professional learner
  • Location
    Canada
  • Work
    Full stack developer
  • Joined

More fromFlávia Bastos

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp