python - 是否有更多的 pythonic,可能是一个衬里,来迭代列表中的字符串?

标签 python string list iteration

<分区>

字符串是可迭代的。 列表是可迭代的。 对于字符串列表,列表和字符串都可以通过嵌套循环进行迭代。

例如:

input = [ 'abcdefg', 'hijklmn', 'opqrstu']
for item in input:
     for letter in item:
        print letter

输出:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u

看来我们可以在字符串的迭代中进行迭代,即迭代“abcdefg”的每个字母。是否有一种更 pythonic 的方式可以像上面那样迭代,可能在一个语句中?

我重新阅读了 Python Cookbook 的 Learning Python 第 4 章和第 1 章,并查看了这里 in python: iterate over each string in a list ,这里Displaying and iterating a list within a string? .

最佳答案

您可以使用 itertools.chain.from_iterable() :

>>> from itertools import chain
>>> input = ['abcdefg', 'hijklmn', 'opqrstu']
>>>
>>> for letter in chain.from_iterable(input):
...     print letter
... 
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u

关于python - 是否有更多的 pythonic,可能是一个衬里,来迭代列表中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23936239/

相关文章:

java - 使用自定义比较器排序列表不起作用

Python:创建一个包含字典的列表

python - TKinter - 如何从 Entry() 添加两个数字

java - 使用正则表达式将字符串数据的键和值格式化为 json 键值对

python - 使用 boto3 列出存储桶的内容

c - 尝试将数组转换为具有空字符的字符串时程序崩溃

regex - 戈兰正则表达式 : FindAllStringSubmatch to []string

python - 将列表输出为列

python - 如何使用 Flask HTTP Auth 为 Web 服务实现 "Incorrect username/password"提示?

python - 视频上的 cv2.hough 圆圈错误