首页 > 解决方案 > 遍历列表 A 中的组并乘以列表 B 中的项目

问题描述

我想将前 9 项中的每一项乘以 中listA的第一项ListB,然后将下一组 9 项中的项ListA乘以 中的第二项listB,依此类推ListA。到目前为止,我有以下但它不起作用——newlist只包含一组 9 项(应该是 12 组 9 项)。

k = 0
n = 0
for i, factor in enumerate(listA[k:k+9]):
    newlist.append(factor * ListB[n])
    k += 9
    n += 1

标签: python

解决方案


选项 1:带有嵌套 for 循环的列表理解

此解决方案在列表理解中使用嵌套for循环。itertools.islice允许我们在不形成中间列表的情况下构建结果。

from itertools import islice

A = list(range(1, 28))
B = list(range(1, 4))

res = [i*B[k] for k in range(int(len(A)/9)) for i in islice(A, k*9, (k+1)*9)]

print(res)

[1, 2, 3, 4, 5, 6, 7, 8, 9,
 20, 22, 24, 26, 28, 30, 32, 34, 36,
 57, 60, 63, 66, 69, 72, 75, 78, 81]

选项 2:使用 zip + itertools.repeat 进行列表理解

itertools.repeat重复一个元素n次。与zip和一起itertools.chain,您可以将其操作为所需的可迭代对象。

from itertools import chain, repeat

B_repeated = chain.from_iterable(zip(*repeat(B, 9)))
res = [i*j for i, j in zip(A, B_repeated)]

选项 3:numpy.repeat

如果您可以使用 3rd 方库,请numpy提供一个简单的解决方案:

import numpy as np

res = A * np.repeat(B, 9)

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9,
       20, 22, 24, 26, 28, 30, 32, 34, 36,
       57, 60, 63, 66, 69, 72, 75, 78, 81])

推荐阅读