Home > Software engineering >  summing same numbers of different lists into another list
summing same numbers of different lists into another list

Time:12-28

#Now I know there are easier methods, but I need to make it in a #function and this is my try. Now it isn't working, but could you pls #help me?

def intersection(l1, l2):
    l3 = []
    for x in range(0, len`length `(l1)):
        if x == l2:
            l3.append(x)
    return l3

print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))

CodePudding user response:

The best / fastest way to do this is to use set.intersection:

def intersection(l1, l2):
     return set(l1).intersection(l2)

CodePudding user response:

You are trying to iterate integers from 0 to len(l1) instead of the iterating list items. You should use

for x in l1:

instead of

for x in range(0, len`length `(l1)):

Also you have an error in comparing items. You should use:

if x in l2:

instead of

if x == l2:

Full code sample:

def intersection(l1, l2):
    l3 = []
    for x in l1:
        if x in l2:
            l3.append(x)
    return l3

print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))

CodePudding user response:

You can use numpy's np.intersect1d method.

import numpy as np
def intersection(l1, l2):
    return np.intersect1d(l1,l2).tolist()
print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))

Output :

[1, 4]

CodePudding user response:

You need to iterate both lists simultaneously, sum each pair and put it into new list.

def intersection(l1, l2):
    result = []
    for item1, item2 in zip(l1, l2):
        result.append(item1   item2)
    return result

print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))


  • Related