列表中数字的乘法(Python)

时间:2018-04-17 12:42:05

标签: python list multiplication

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]

但我知道它不起作用,我不知道如何处理这些数据。

2 个答案:

答案 0 :(得分:2)

这是一种方式。

$ sed 's/\w*[0-9]\w*\s*//g' infile
asdkbasdnas jksndkasnd jkasdsa

替代解决方案:

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]

答案 1 :(得分:0)

这是使用combinations_with_replacement()中的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]