我有两个列表:
List1 = [[A,1],[B,2],[C,3]]
List2 = [[A,4],[B,5],[C,6]]
我期待着这个:
iteration1 ->
List1 = [[A,1],[B,2],[C,3]]
List2 = [[A,4],[B,5],[C,6]]
sop = (1*4)+(2*5)+(3*6) = 32
iteration2 ->
List1 = [[A,1],[B,2],[C,3]]
List2 = [[B,5],[C,6],[A,4]] #only second list shifts by one to the left
sop = (1*5)+(2*6)+(3*4) = 29
iteration2 ->
List1 = [[A,1],[B,2],[C,3]]
List2 = [[C,6],[A,4],[B,5]] #only second list shifts by one to the left
sop = (1*6)+(2*4)+(3*5) = 29
结果列表应显示以下内容:
resultlist = [32,29,29]
我无法弄清楚如何在python中编写代码,有人可以帮我解决这个问题吗?
答案 0 :(得分:3)
您应该使用一个变量(offset
)来确定旋转B的数量,而不是物理地移动列表。索引上的模数运算可用于模拟循环列表。
def products(A, B):
out = []
n = len(A)
for offset in range(n):
out.append(sum( A[i] * B[ (i + offset) % n ] for i in range(n)))
return out
假设输入是数字数组,例如products([1,2,3],[4,5,6])
答案 1 :(得分:2)
你可以itertools.cycle
覆盖List2,在每个循环结束时跳过一个:
from itertools import cycle
List1 = [['A',1],['B',2],['C',3]]
List2 = cycle([['A',4],['B',5],['C',6]])
resultlist = []
for _ in List1:
resultlist.append(sum(a[1]*b[1] for a,b in zip(List1, List2)))
next(List2) # skip one of the cycle
print(resultlist)
输出:
[32, 29, 29]