如何使用多个列表执行计算?

How to perform calculations with multiple lists?

所以我有 4 个列表,其中 2 个在函数内部创建,2 个在函数外部创建。

list_3 = []
list_4 = []
def create_list_3_4():
    a = 4
    b = 5
    list_3.append(a) 
    list_3.append(b)

    c = 8
    d = 9
    list_4.append(c)
    list_4.append(d)

    return list_3, list_4

list_1 = [10.5, 8.5]
list_2 = [12.6, 11.5]


value_1 = [x[0] for x in list_1] - [x[0] for x in list_2]
value_2 = [x[0] for x in create_list_3_4()] - [[x[0] for x in create_list_3_4()]]
value_3 = value_2 / value_1
new_list = []
new_list.append(value_3)
print(new_list)

对于 list_2 中的每个项目,我想要减去 list_1 中的每个项目。所以 12.6 - 10.511.5 - 8.5 等。对于函数内的列表,我想做同样的事情。所以 8 - 49 - 5 等等...

最后我想把 12.6 - 10.58 - 4 的答案分开放在一起 new_list.

这是我当前的输出:

    value_1 = [x[0] for x in list_1] - [x[0] for x in list_2]
TypeError: 'float' object is not subscriptable

这是我想要的输出:

[1.904, 1.333]

计算的额外信息:

1.904 = (8 - 4 = 4 / 12.6 - 10.5 = 2.1)
1.333 = (9 - 5 = 4 / 11.5 - 8.5 = 3)

您可以使用zip将四个列表组合在一起,并在列表理解中执行操作:

def create_list_3_4():
    list_3 = []
    list_4 = []
    a = 4
    b = 5
    list_3.append(a) 
    list_3.append(b)

    c = 8
    d = 9
    list_4.append(c)
    list_4.append(d)

    return list_3, list_4

list_1 = [10.5, 8.5]
list_2 = [12.6, 11.5]
list_3,list_4 = create_list_3_4()

new_list = [(x4-x3)/(x2-x1) for x1,x2,x3,x4 in zip(list_1,list_2,list_3,list_4)]

print(new_list)
[1.904761904761905, 1.3333333333333333]

要在整个列表之间执行操作,您 could/should 使用 numpy:

import numpy as np

list_1 = np.array([10.5, 8.5])
list_2 = np.array([12.6, 11.5])
list_3,list_4 = map(np.array,create_list_3_4())

new_list = (list_4 - list_3) / (list_2 - list_1)

print(new_list)
[1.9047619  1.33333333]

注意要在函数内部初始化list_3和list_4否则每次都会添加内容所以不能多次使用被调用(使列表越来越大并且与 list_1 和 list_2 不兼容)

这可以通过列表理解来实现,正如您已经开始的那样,以及 zip() 函数:

list_1 = [10.5, 8.5]
list_2 = [12.6, 11.5]
value_1 = [num_2 - num_1 for num_1, num_2 in zip(list_1, list_2)]

对于第二部分,您需要在最终理解之前定义 list_3list_4

list_3, list_4 = create_list_3_4()
value_2 = [num_2 - num_1 for num_1, num_2 in zip(list_3, list_4)]

然后划分列表:

value_3 = [num_2 / num_1 for num_1, num_2 in zip(value_1, value_2)]

可以合并这些步骤以减少运行时间(尽管如果您想要更清楚,这并不是完全必要的):

value_3 = [(num_4 - num_3) / (num_2 - num_1) for num_1, num_2, num_3, num_4 in zip(list_1, list_2, list_3, list_4)]

请注意,如果您打算使用可迭代对象进行数学运算,您最好使用 NumPy 模块,这样可以简化操作(假设每个列表都已转换为数组) :

value_3 = (list_4 - list_3) / (list_2 - list_1)