简体   繁体   中英

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. I have tried converting them to floats using float() , but it does not work.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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