[英]Iterating through multiple lists with same index position in python
I am new to python and I was just trying some list manipulations. 我是python的新手,我只是尝试了一些列表操作。 I have three lists
我有三个清单
A = [10,20,30,40,50,60]
B = [22,44,66,88,12,10]
C = [2,4,6,8,10,20]
I want to iterate over these three lists and for each value of CI want to add half of that value to the corresponding values of A and B. For example for the 1st iteration - half = 2/2= 1 So A = 10 + 1 and B = 22+1 So the final lists should look something like this 我想迭代这三个列表,并且CI的每个值都希望将该值的一半添加到A和B的相应值。例如,对于第一次迭代 - half = 2/2 = 1所以A = 10 + 1并且B = 22 + 1所以最终的列表看起来应该是这样的
A = [11,22,33,44,55,70]
B = [23,46,69,92,17,20]
C = [2,4,6,8,10,20]
As long as the lists all have the same lengths, you can iterate with enumerate()
function: 只要列表都具有相同的长度,您就可以使用
enumerate()
函数进行迭代:
for i, n in enumerate(C):
A[i] += n/2
B[i] += n/2
>>> A
[11, 22, 33, 44, 55, 70]
>>> B
[23, 46, 69, 92, 17, 20]
>>> A, B = zip(*((a + c/2, b + c/2) for a, b, c in zip(A, B, C)))
ITs best to use Numpy
arrays. 最好使用
Numpy
阵列。
import numpy as np
A, B, C = map(np.array, [A, B, C])
A, B = A - C/2, B - C/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.