Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 2 lists (not using pandas)

I am trying to do an inner join with 2 lists in python, without using pandas or numpy libraries.

The function combine has parameters: One: first list; Two: second list; left: indice of column in first list; right: indice of column in second list

I am trying to combine the 2 lists based on the indices of each list having elements that equal and then joining their elements together.

So far I have this code:

def combine(one, two, left, right):
    combined = []
    for x in one:                         #for elements in list one
        for y in two:                     #for elements in list two
            if x[left] == y[right]:       #if both elements at each indice equal
                combined = [x,y]          #place x and y values into combined list

    print(combined)


one = [['apple', 'fruit'],
       ['broccoli', 'vegetable']]
two = [['fruit', '1'],
       ['vegetable', '1']]

combine(one, two, 1, 0 )

For some reason i am getting an empty list: []

The desired output is:

 [['apple', 'fruit', 'fruit', '1'],
 ['broccoli', 'vegetable', 'vegetable', '1']]

Any ideas/tips of how i can accomplish this?

like image 838
Omi in a hellcat Avatar asked Oct 21 '25 03:10

Omi in a hellcat


2 Answers

I hope this code helps!

def combine(one, two, left, right):
    combined = []
    for x in one:  #for elements in list one
        for y in two:  #for elements in list two
            if x[left] == y[right]:  #if both elements at each indice equal
                combined.append(
                    x + y)  #place x and y values into combined list

    print(combined)


one = [['apple', 'fruit'], ['broccoli', 'vegetable']]
two = [['fruit', '1'], ['vegetable', '1']]

combine(one, two, 1, 0)
like image 89
Mark White Avatar answered Oct 25 '25 07:10

Mark White


From my point of view, you should be calling the function like this:

combine(one, two, 1, 0 )

Since the position one[1] is the one that has the common value with two[0].

like image 20
Marcos Jota Avatar answered Oct 25 '25 05:10

Marcos Jota