简体   繁体   English

从列表中减去值,收到“生成器对象不可下标”错误

[英]Subtracting values from lists, received "generator object is not subscriptable" error

I am trying to subtract the values of two lists from each other.我试图从彼此中减去两个列表的值。 Like this:像这样:

    a = [1,2,3,4,5] b = [1,2,3,4,5] 
    a - b = [0,0,0,0,0] 

However, the loop I'm trying to do it in keeps giving me "generator object is not subscriptable" and refers to this section of my code:但是,我尝试执行的循环不断给我“生成器对象不可下标”,并引用了我的代码的这一部分:

      distances_1 = [a[z] - b[z] for z in x]

My sample data differs in dimensions for each file;我的样本数据在每个文件的维度上都不同; though, here is an example of what it looks like:不过,这是一个示例:

    x = [1.2323 2.5689] y = [2.3565 3.58789]

Here is an example of my code:这是我的代码示例:

    def distances_z(x,y):
    dct = {}
    for i in y:
        a = (i.split(' ',)[0] for i in y)
        for z in x:
            b = (z.split(' ',1)[0] for z in x)
            distances_1 = [a[z] - b[z] for z in x]
            return distances_1
        dct[i +"_"+"list"] = [distances_1]
    print(dct)
    return dct

I believe it to be a problem with my a and b variables not being recognized as integers.我认为这是我ab变量未被识别为整数的问题。 I have tried converting them to floats using float() , but it does not work.我尝试使用float()将它们转换为浮点数,但它不起作用。

Try this试试这个

a = [1,2,3,4,5] 
b = [1,2,3,4,5] 
c = [x[0] - x[1] for x in zip(a,b)]

Gives output给出输出

[0, 0, 0, 0, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM