Py学习  »  Python

Python:将列表中的元素相乘

moolenschot • 4 年前 • 1593 次点击  

如何使用for循环将列表中的每个元素与列表中的每个其他元素相乘?像这样:[1,3,5,7]应该像这样相乘:1*3+1*5+1*7+3*5+3*7+5*7

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128966
文章 [ 3 ]  |  最新文章 4 年前
Chris
Reply   •   1 楼
Chris    4 年前

您可以将生成的每个组合相乘 combinations 把它们加起来。

from itertools import combinations
from operator import mul
l = [1, 3, 5, 7]

sum([mul(*x) for x in combinations(l,2)])

输出

86
Yevgeniy Kosmak
Reply   •   2 楼
Yevgeniy Kosmak    4 年前

当然可以:

a = [1, 3, 5, 7]
s = 0
for i in range(len(a)):
    for j in range(i + 1, len(a)): 
        s += a[i] * a[j]
print(s)
RomanG
Reply   •   3 楼
RomanG    4 年前

不使用列表索引:

listit = [1, 5, 3, 7]

x_position = 0
result = 0

for x in listit:
    x_position += 1
    y_position = 0
    for y in listit:
        y_position += 1
        if x_position < y_position:
            print(f"{x} * {y}")
            result += x * y
            print(result)

print(result)