python-3.x 对两个列表所包含的每个元组的值求和,问题是它们加在一起,但不求和

luaexgnf  于 2023-01-06  发布在  Python
关注(0)|答案(3)|浏览(129)

我将两个列表中的每个元组的值相加,得到的输出是:125, 200.0, 100.0.
问题是它们不求和,而是像[(87.5, 37.5), (125.0, 75.0), (50.0, 50.0)]这样相加。我需要firstsecond保持和我的一样,* 不改变任何括号。* 我在stackoverflow上搜索了许多类似的答案,但没有找到适合我的答案。
我该如何编辑calc并修复它?谢谢!
代码:

first = [(87.5,), (125.0,), (50.0,)]
second = [(37.5,), (75.0,), (50.0,)]

calc = [x + y for x, y in zip(first, second)]
print(calc)
ippsafx7

ippsafx71#

这两个列表中的所有值都被 Package 在元组中,因此您应该相应地将它们解包:

calc = [x + y for [x], [y] in zip(first, second)]
juud5qan

juud5qan2#

问题是你试图添加元组(如果你键入(x)或(y),你会看到那些是元组值,而不是你所拥有的特定浮点数)。如果你想添加元组内部的值,那么你必须访问元素,你可以这样做:

first = [(87.5,), (125.0,), (50.0,)]
    second = [(37.5,), (75.0,), (50.0,)]
    
    calc = [x[0] + y[0] for x, y in zip(first, second)] # accessing the first element of x and y -- as there is only 1 element in each of the tuples. 
    # if you had more elements in each tuple you could do the following: calc = [sum(x) + sum(y) for x, y in zip(first, second)]
    print(calc)
    print(first, second)
cqoc49vn

cqoc49vn3#

如果安装了numpy并且它是您代码的一部分,则有一种方法可以使用numpy

import numpy as np

first = [(87.5,), (125.0,), (50.0,)]
second = [(37.5,), (75.0,), (50.0,)]

(np.array(first) + np.array(second)).T.tolist()[0]

输出

[125.0, 200.0, 100.0]

相关问题