简体   繁体   中英

Pythonic way to iterate through list of strings?

At the moment I have the following as a way of putting the characters in a sort of visual text-map into a dict. I am wondering though, if there's a really nice concise, pythonic way of doing this double iteration. Any ideas?

lines = ['abc','456','xyz']
chars = {}
for i, row in enumerate(lines):
    for j, c in enumerate(row):
        chars[i,j] = c

You could express it as a dictionary comprehension:

chars = {(i, j): c for i, row in enumerate(lines) for j, c in enumerate(row)}

It's fundamentally the same iteration, only expressed a bit differently.

Use a dict comprehension. The key to reading nested comprehensions: "Just read them like normal loops, with the “big loop” described first and the subsequent loops nested inside of it" 1

In [1]: lines = ['abc','456','xyz']

In [2]: {(i,j): c for i, row in enumerate(lines) for j, c in enumerate(row)}
Out[2]: 
{(0, 0): 'a',
 (0, 1): 'b',
 (0, 2): 'c',
 (1, 0): '4',
 (1, 1): '5',
 (1, 2): '6',
 (2, 0): 'x',
 (2, 1): 'y',
 (2, 2): 'z'}

You can split the comprehension to multiple lines, to make it more readable. If you look closely it is actually very similar to a regular loop, only the last line is brought to the start.

In addition to that I would recommend reading a blog post by Brandon Rhodes: "I finally understand nested comprehensions"

# Comprehension                       # Regular for loop

{(i,j):c                              # chars = {}
    for i, row in enumerate(lines)    # for i, row in enumerate(lines):
        for j, c in enumerate(row)}   #     for j, c in enumerate(row):
                                      #          chars[i,j] = c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM