简体   繁体   中英

How do I subtract lists from each other?

I have two functions that output 2 lists respectively using what I've coded below. I'm trying to subtract one list from another.

def ok(n):
    results = []
    for n in range (2, n+1):
        s = Sup(n)
        results.append(s)
    return(results)


def uk(m):
    result = []
    for m in range (2, m+1):
        t = Sdown(m)
        result.append(t)
    return(result)
print(ok(7))
print(uk(7))

uk(7) - ok(7)

When I call, ok(7) I get:

[1.0833333333333333, 1.7178571428571427, 2.380728993228994, 3.05849519543652, 3.7438909037057684, 4.433147092589173]

Similarly for uk(7), I get:

[2.083333333333333, 2.7178571428571425, 3.380728993228993, 4.058495195436521, 4.743890903705768, 5.433147092589174]

I've tried then performing the operation: uk(7) - ok(7) but get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-3aa3eb52f7a8> in <module>
     18 print(uk(7))
     19 
---> 20 uk(7) - ok(7)

TypeError: unsupported operand type(s) for -: 'list' and 'list'

How can I fix this?

You Cannot subtract list from another list. Try using numpy or Zip

>>> l1 = [1.0833333333333333, 1.7178571428571427, 2.380728993228994, 3.05849519543652, 3.7438909037057684, 4.433147092589173]
>>> l2 = [2.083333333333333, 2.7178571428571425, 3.380728993228993, 4.058495195436521, 4.743890903705768, 5.433147092589174]

>>> import numpy as n
>>> n.array(l2) - n.array(l1)
    array([ 1.,  1.,  1.,  1.,  1.,  1.])

Use zip to pair the elements of your lists, and a list comprehension to generate the output list:

difference = [u - o for u, o in zip(uk(7), ok(7))]

zip yields tuples by combining the elements of your two lists uk(7) and ok(7) :

  • (<first item of uk(7)>, first item of ok(7)>)
  • (<second item of uk(7)>, second item of ok(7)>)
  • ...

In the for loop, the two values in the tuple are unpacked to u and o , and the difference list is built of the resulting u - o values.

Search about 'list comprehension' if you don't know about it, you'll find plenty of information.

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