简体   繁体   中英

Subtracting two lists together, if value is negative, take the value from the first list (Python)

For example, there are 2 lists.

list_1= [1, 2, 3]
list_2 = [2, 0, 4]

Simple subtraction of the two lists using operator.sub would return:

list_3 = [-1, 2, -1]

I would like to return another list_4:

list_4 = [1, 0, 3]

What list_4 means essentially is that if the result of list_3 is negative, I would take the value of list_1. If the result of list_3 is positive, I would take the value of list_2.

Therefore list_4 should return 1 (from list_1), 0 (from list_2) and 3 (from list_1) respectively.

I understand this probably has something to do with list comprehension, but I can't seem to figure it out myself. Would appreciate any help that I can get!

list comprehension:

[x if x < y else y for x,y in zip(list_1, list_2)]

Result:

[1, 0, 3]

Alternatives:

  • [min(x,y) for x,y in zip(list_1, list_2)]
  • [min(*e) for e in zip(list_1, list_2)]
  • import numpy as np
    np.minimum(list_1, list_2).tolist()

probably this isn't the most pythonic way. I am assuming zero is positive.

list_4 = []
for i, element in enumerate(list_3):
   if element < 0:
      list_4.append(list_1[i])
   else: # element >= 0
      list_4.append(list_2[i])

That should work for you:

list_4 = []
for i, num in enumerate(list_3):
    list_4.append(list_1[i] if element < 0 else list_2[i])

With list comprehension..

list_4 = [i if k<0 else j for i,j,k in zip(list_1, list_2, list_3)]

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