python - 在python中将列表中的数字相乘

标签 python python-3.x list

我有一个列表:

lst = [[7], [4, 3, 5, 8], [1, 3]]

如何将 list 中的每个元素与其位置相乘:

[[7 * 0],[4 * 0 + 3 * 1 + 5 * 2 + 8 * 3], [1 * 0 + 3 * 1]]

并打印答案:

answer = [[0], [37], [3]]

最佳答案

您可以将列表理解与 sumenumerate 结合使用:

L = [[7], [4, 3, 5, 8], [1, 3]]

res = [[sum(i*j for i, j in enumerate(sublist))] for sublist in L]

print(res)

[[0], [37], [3]]

或者,如果您乐于使用第 3 方库,则可以使用 NumPy:

import numpy as np

L = [[7], [4, 3, 5, 8], [1, 3]]

res = [np.arange(len(sublist)).dot(sublist) for sublist in L]

print(res)

[0, 37, 3]

关于python - 在python中将列表中的数字相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51337313/

相关文章:

python - SQLAlchemy 混合表达式访问不同的行

python - 如何在Python中从现有的父类(super class)类型对象实例化子类类型变量

python - 如何将数据发布到网站并立即将您重定向到另一个网站

python-3.x - 连接拒绝在 docker 上使用 Postgresql

python - 如何从字符串的排列列表中分离元素?

python - 列表搜索中的快速字符串

python - 在 Python 中优雅地抑制斜纹输出

c# - 如何根据属性对 C# 列表进行排序?

c# - 初始化编号字符串列表的快速方法?

python - 如何制作良好的可重复 Pandas 示例