[英]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.
我想知道,如果有一个非常好的简洁,pythonic方式做这个双重迭代。 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
阅读嵌套理解的关键: “只需读取它们就像普通循环一样,首先描述”大循环“,然后将嵌套在其中的后续循环” 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" 除此之外,我建议阅读Brandon Rhodes的博客文章: “我终于理解了嵌套的理解”
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.