元素乘以元素乘以一元

时间:2015-09-19 05:30:54

标签: python list

我有两个清单:

a = [[A,1],[B,2],[C,3]]
b = [[X,4],[Y,5],[Z,6]]

我试图将元素乘以元素,使得我保持“a”不变,并在每次迭代中将“b”移动一个位置。

1st iteration:
1*4+2*5+3*6 = 32
2nd iteration:
1*5+2*6+3*4 = 29
3rd iteration:
1*6+2*4+3*5 = 29

将所有结果存储在列表c中。我希望c是:

c = [32,39,29]

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:3)

一种简单的方法是使用切片:

c = []
for i in range(len(b)):
    c.append(sum(x*y for x, y in zip(a, b[i:] + b[:i])))

示例运行:

In [1]: a = [1, 2, 3]
   ...: b = [4, 5, 6]
   ...: 

In [2]: c = []
   ...: for i in range(len(b)):
   ...:     c.append(sum(x*y for x, y in zip(a, b[i:] + b[:i])))
   ...:     

In [3]: c
Out[3]: [32, 29, 29]

在您的情况下,您可能需要将x*y替换为x[1]*y[1]

然而,这会在每次迭代时创建b的副本。您可能只想使用循环:

import itertools as it

c = []
for k in range(len(b)):
    res = 0
    for i, j in enumerate(it.chain(range(k, len(b)), range(k))):
        res += a[i]*b[j]
    c.append(res)

或者您可以使用collections.deque来存储索引:

from collections import deque

c = []
b_indices = deque(range(len(b)))

for _ in range(len(a)):
    c.append(sum(x*b[j] for x, j in zip(a, b_indices))
    b_indices.rotate(-1)

答案 1 :(得分:0)

您可以使用此解决方案。这是在每次迭代中修改b。

lst =[]
for i in range(len(a)):
    value= [a[i][1]*b[i][1] for i in range(len(b))]
    lst.append(sum(value))
    b.insert(0,b.pop())
print lst

输出:

[32,29,29]

如您所希望的完整解决方案,请参阅:

lst =[]
summed =0
length =len(a)
for x in range(len(a)):
    print "Iteration ",x+1
    for i in range(length):
        print a[i][1],"*",b[i][1],
        summed +=a[i][1]*b[i][1]
        if i<length-1:
            print "+",

        else:
            print "=", summed
            lst.append(summed)
            summed=0
    b.insert(0,b.pop())

print lst

输出:

Iteration  1
1 * 4 + 2 * 5 + 3 * 6 = 32
Iteration  2
1 * 6 + 2 * 4 + 3 * 5 = 29
Iteration  3
1 * 5 + 2 * 6 + 3 * 4 = 29
[32, 29, 29]