gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:14:02 30 4
gpt4 key购买 nike

我有一个列表:

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com