Ziz*_*upp 8 python list-comprehension list
我有以下字符串列表:
l1 = ['one','two','three']
Run Code Online (Sandbox Code Playgroud)
我想获得一个列表,例如,这些相同的元素重复了n多次。如果n=3我得到:
l2 = ['one','one','one','two','two','two','three','three','three']
Run Code Online (Sandbox Code Playgroud)
我正在尝试的是这样的:
l2 = [3*i for i in l1]
Run Code Online (Sandbox Code Playgroud)
但我得到的是:
l2 = ['oneoneone','twotwotwo','threethreethree']
Run Code Online (Sandbox Code Playgroud)
如果我试试这个:
l2 = [3*(str(i)+",") for i in l1]
Run Code Online (Sandbox Code Playgroud)
我获得:
l2 = ['one,one,one','two,two,two','three,three,three']
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
Azi*_*ziz 13
l2 = [j for i in l1 for j in 3*[i]]
Run Code Online (Sandbox Code Playgroud)
这给出:
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']
Run Code Online (Sandbox Code Playgroud)
这相当于:
l2 = []
for i in l1:
for j in 3*[i]:
l2.append(j)
Run Code Online (Sandbox Code Playgroud)
请注意,3*[i]创建一个包含 3 个重复元素的列表(例如['one', one', 'one'])
您可以使用 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']
Run Code Online (Sandbox Code Playgroud)
所以你可以定义一个重复元素的函数,如下所示:
def repeat_elements(l, n)
return list(chain.from_iterable([[e]*n for e in l]))
Run Code Online (Sandbox Code Playgroud)
如果你想使用纯列表理解
[myList[i//n] for i in range(n*len(myList))]
Run Code Online (Sandbox Code Playgroud)
解释:
如果原始列表有 k 个元素,则重复因子为 n => 最终列表中的项目总数:n*k
要将范围 n*k 映射到 k 个元素,请除以 n。记住整数除法