在Python中为列表的每个元素重复

时间:2022-05-22 14:31:14

I have a list a = [3,7,4]

我有一个清单a = [3,7,4]

I want to generate a list repetition of a sequence generated from each element of list like that:

我想生成从列表的每个元素生成的序列的列表重复,如下所示:

b = [1,1,1,2,2,2,2,2,2,2,3,3,3,3]

b = [1,1,1,2,2,2,2,2,2,2,3,3,3,3]

2 个解决方案

#1


-1  

Try like this.

试试这样吧。

result = []
for i,j in enumerate(a):
    result += [i+1 for n in range(j)]

Result

[1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3]

#2


-1  

input:

a = [3,7,4]
b = [x for x in range(len(a)+1)[1::] for j in range(a[x-1])]

result:

[1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3]

#1


-1  

Try like this.

试试这样吧。

result = []
for i,j in enumerate(a):
    result += [i+1 for n in range(j)]

Result

[1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3]

#2


-1  

input:

a = [3,7,4]
b = [x for x in range(len(a)+1)[1::] for j in range(a[x-1])]

result:

[1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3]

相关文章