如何将一个列表中的第一个项目附加到另一个列表中

时间:2019-03-07 08:20:55

标签: python-3.x

假设我有一个列表[100,200,300,400]和另一个列表[2,3,1,2] 我希望输出为[100,100,200,200,200,300,400,400]

4 个答案:

答案 0 :(得分:1)

您可以创建一个新列表,如下所示:

l1 = [100,200,300,400]
l2 = [2,3,1,2]

zipped_data = list(zip(l1,l2))

result = [x[0] for x in zipped_data for i in range(x[1])]

print(result)

输出:

[100, 100, 200, 200, 200, 300, 400, 400]

答案 1 :(得分:1)

a = [100,200,300,400]
b = [2,3,1,2]
c=[i[0] for i in zip(a,b) for j in range(i[1])]
print(c)

输出

[100, 100, 200, 200, 200, 300, 400, 400]

答案 2 :(得分:0)

第一种方法是:

a = [100,200,300,400]
b = [2,3,1,2]
c = [i*100 for i in b]
d = (a + c).sort()

第二种方法是:

import numpy as np
a = [100,200,300,400]
b = [2,3,1,2]
c = np.r_[np.array(a), np.array(b)*100]
d = c.sort()

答案 3 :(得分:0)

这可以使用for循环来实现。这是基本方法。

l1 = [100,200,300,400]
l2 = [2,3,1,2]
result = []
for i in range(len(l2)):
    for j in range(l2[i]):
        result.append(l1[i])
print(result)