如何从列表中分配值?

时间:2019-05-25 21:46:24

标签: python

我的列表中有元组:

a = [((1, 6), (8, 2)), ((8, 2), (6, 3)), ((6, 3), (9, 4)), ((9, 4), (5, 7))]

我想分配列表中的所有值,例如:

A = [1,6], B = [8,2]

A = [8,2], B = [6,3]

然后在元素之间进行计算,并将结果打印在屏幕上

C1 = (A[1]+B[1],A[2]+B[2])

C2 = (A[1]+B[1],A[2]+B[2])

谢谢!

X = [1,8,6,9,5]

Y = [6,2,3,4,7]

res = list(zip(X,Y))

a = list(zip(res, res[1:]))

print(a)

我想不出如何在列表中分配A和B

3 个答案:

答案 0 :(得分:1)

此列表理解应执行您描述的操作

>>> [tuple(sum(i) for i in zip(x, y)) for x, y in a]
[(9, 8), (14, 5), (15, 7), (14, 11)]

答案 1 :(得分:0)

>>> a = [((1, 6), (8, 2)), ((8, 2), (6, 3)), ((6, 3), (9, 4)), ((9, 4), (5, 7))]
>>> A = a[0][0] # First item's ((1,6), (8,2)) first item (1,6)
>>> B = a[0][1] # First item's ((1,6), (8,2)) second item (8,2)
>>> A
(1, 6)
>>> B
(8, 2)
>>>

答案 2 :(得分:0)

使用lambda

a = [((1, 6), (8, 2)), ((8, 2), (6, 3)), ((6, 3), (9, 4)), ((9, 4), (5, 7))]
sol = list(map(lambda x:(x[0][0]+x[1][0],x[0][1]+x[1][1]), a))
print(sol)

输出

[(9, 8), (14, 5), (15, 7), (14, 11)]