列表理解:将每个字符串乘以一个列表

时间:2016-07-23 16:01:26

标签: python list python-3.x list-comprehension

我有一个字符串列表,希望多次获得一个包含每个元素的新列表。

lst = ['abc', '123']
n = 3

我可以用for循环来做到这一点:

res = []
for i in lst:
    res = res + [i]*n
print( res )

['abc', 'abc', 'abc', '123', '123', '123']

如何使用列表理解?

到目前为止我最好的尝试:

[ [i]*n for i in ['abc', '123']  ]
[['abc', 'abc', 'abc'], ['123', '123', '123']]

2 个答案:

答案 0 :(得分:6)

使用nested list comprehension

>>> lst = ['abc', '123']
>>> n = 3
>>> [i for i in lst for j in range(n)]
['abc', 'abc', 'abc', '123', '123', '123']

这背后的想法是,你遍历列表两次,然后打印每个元素三次。

请参阅What does "list comprehension" mean? How does it work and how can I use it?

答案 1 :(得分:1)

也可以这样做:

>>> lst = ['abc', '123']
>>> n=3
>>> [j for i in lst for j in (i,)*n]
['abc', 'abc', 'abc', '123', '123', '123']