列表中数字的乘法 (Python)
Multiplication of numbers in a list (Python)
Python 中是否有任何函数可以将列表中的数字相互相乘?
input -> A = [1,2,3,4]
output -> B = [1*1, 1*2, 1*3, 1*4, 2*2, 2*3, 2*4, 3*3, 3*4, 4*4]
或者有人可以帮助我创建自己的函数吗?我有超过 8000 条记录,我不想手动完成。
到目前为止我唯一想到的是:
for i in list:
list[i] * list[i+1]
但我知道这行不通,而且我不知道如何处理这些数据。
这是一种方式。
A = [1,2,3,4]
res = [i*j for i in A for j in A[A.index(i):]]
# [1, 2, 3, 4, 4, 6, 8, 9, 12, 16]
备选方案:
n = len(A)
res = [A[i]*A[j] for i in range(n) for j in range(i, n)]
这是使用 combinations_with_replacement()
from itertools
的替代方法:
>>> A = [1,2,3,4]
>>> from itertools import combinations_with_replacement
>>> [a * b for a, b in combinations_with_replacement(A, 2)]
[1, 2, 3, 4, 4, 6, 8, 9, 12, 16]
Python 中是否有任何函数可以将列表中的数字相互相乘?
input -> A = [1,2,3,4]
output -> B = [1*1, 1*2, 1*3, 1*4, 2*2, 2*3, 2*4, 3*3, 3*4, 4*4]
或者有人可以帮助我创建自己的函数吗?我有超过 8000 条记录,我不想手动完成。
到目前为止我唯一想到的是:
for i in list:
list[i] * list[i+1]
但我知道这行不通,而且我不知道如何处理这些数据。
这是一种方式。
A = [1,2,3,4]
res = [i*j for i in A for j in A[A.index(i):]]
# [1, 2, 3, 4, 4, 6, 8, 9, 12, 16]
备选方案:
n = len(A)
res = [A[i]*A[j] for i in range(n) for j in range(i, n)]
这是使用 combinations_with_replacement()
from itertools
的替代方法:
>>> A = [1,2,3,4]
>>> from itertools import combinations_with_replacement
>>> [a * b for a, b in combinations_with_replacement(A, 2)]
[1, 2, 3, 4, 4, 6, 8, 9, 12, 16]