python - 遍历列表 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
解决方案
选项 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])
推荐阅读
- c# - 为什么我的播放器在 Z = 990 处停止随机前进
- java - 无法在 Eclipse 的 Maven 中获取“Gluon Glisten”依赖库
- go - Knative pod http 请求
- docker - 在 docker-compose.yml 中定义局部变量?
- mysql - 用另一个表的列更新一个表的一列(一对多关系)
- javafx - 如何将多个控制器连接到一个模型?JavaFX 中的简单窗口应用程序
- java - 如何从可选 Java 对象的数组中删除所有项目?
- java - 我如何串流
和整个数据库使用 JPA? - python - 将多个 xlsx 文件合并到一张纸中
- javascript - 闭包和对父变量的访问不再在执行堆栈上