Python:通过为每个原始元素添加n个元素来扩展字符串列表

9

我有以下字符串列表:

l1 = ['one','two','three']

我想获得一个列表,其中包含相同的元素,重复n次。如果n=3,则会得到:

l2 = ['one','one','one','two','two','two','three','three','three']

我所尝试的是这样的:
l2 = [3*i for i in l1]

但我得到的是这个:

l2 = ['oneoneone','twotwotwo','threethreethree']

如果我尝试这样做:

l2 = [3*(str(i)+",") for i in l1]

我得到:

l2 = ['one,one,one','two,two,two','three,three,three']

我错过了什么?


1
在编程中,“,”不会作为单独的列表元素进行计算,它只是一个带有逗号字符的字符串。 - deceze
1
如果您正在进行代码高尔夫比赛,您可以在这个例子中使用sorted(l1*3,key=l1.index) - ScootCork
4个回答

14
 l2 = [j for i in l1  for j in 3*[i]]

这将给出:

 ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

这相当于:

l2 = []
for i in l1:
    for j in 3*[i]:
       l2.append(j)

请注意3*[i]将创建一个有3个重复元素的列表(例如['one','one','one']


5

你可以使用itertools将列表中的嵌套列表转换成一个列表(高效):

from itertools import chain
l1 = ['one','two','third']
l2 = list(chain.from_iterable([[e]*3 for e in l1]))
# l2 = ['one','one','one','two','two','two','three','three','three']

因此,您可以定义一个像这样重复元素的函数:

def repeat_elements(l, n)
    return list(chain.from_iterable([[e]*n for e in l]))

5

如果您想使用纯列表推导式

 [myList[i//n] for i in range(n*len(myList))]
解释:

如果原始列表有k个元素,重复因子为n => 最终列表中的总项数:n*k

要将范围n*k映射到k个元素,请除以n。记住整数除法。


1
这是一个相当聪明的解决方案。只有几点需要注意:使用整数除法运算符(//)而不是常规除法运算符(/)。此外,如果您没有同时传递三个可能的参数,则将零作为传递给 range() 的第一个参数是多余的。只需将其更改为 range(n*len(myList)) 即可。 - revliscano
谢谢@revliscano。我已经完成了建议的编辑。 - Holy_diver

3
您可以尝试使用 mapsum
print(list(sum(map(lambda x: [x] * 3, l1), [])))

输出

['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接