0

我有两个列表,我正在尝试根据它们出现的次数创建多个数字副本。

numbers = [0, 1, 2]
amount = [1, 2, 3]

我试过了:

total = []
n = 0
for i in range(len(numbers)):
    product = numbers[n] * amount[n]
    n += 1
    total.extend(product)

但我得到了错误:

TypeError: 'int' object is not iterable.

我的预期输出是:

total = [0, 1, 1, 2, 2, 2]
4

2 回答 2

3

利用zip

result = []
for i, j in zip(numbers, amount):
    result.extend([i] * j)

print(result)

[0, 1, 1, 2, 2, 2]
于 2020-08-26T16:07:26.063 回答
2

您的错误在以下行内:

product = numbers[n] * amount[n]

它不会产生一个列表,而是一个整数。因为你将两个数字相乘。

你真正想要的是

product = [numbers[n]] * amount[n]

在这里尝试一下: https ://repl.it/repls/WholeHuskyInterfaces

于 2020-08-26T16:06:35.287 回答