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

2024-06-23 19:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串列表:

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']

我错过了什么


Tags: 字符串in元素l1列表foronethree
3条回答

如果你想使用纯列表理解

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

说明:

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

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

您可以使用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]))
 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']

相关问题 更多 >

    热门问题