简体   繁体   中英

How to subtract all elements in list from one element in another list?

I have a problem with mathematically subtracting all elements of one list against one element of another list. This is what I need:

>>>list1 = [ a, b, c]
>>>list2 = [ d, e, f]    

result = [ d-a, e-a, f-a, d-b, e-b, f-b, d-c, e-c, f-c]

I tried with a nested loop for but it doesn' t work out just fine:

 subtr = [] 
 for i in list1:
    for j in list2:
       subtr.append(j - i)

If someone could please help I would be very thankful!

With list comprehensions and example values

list1 = [ 10, 20, 30]
list2 = [ 1, 2, 3] 

[y - x for x in list1 for y in list2]

Out:

[-9, -8, -7, -19, -18, -17, -29, -28, -27]

Your code does the same. You can test it with example values

subtr = [] 
for i in list1:
    for j in list2:
        subtr.append(j - i)
print(subtr)

Out:

[-9, -8, -7, -19, -18, -17, -29, -28, -27]

Here is a simple solution:

list1 = [1, 2, 3]
list2 = [10, 20, 30]

result = [x-y for y in list1 for x in list2]

Result:

[9, 19, 29, 8, 18, 28, 7, 17, 27]

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