Search code examples
pythonlistnested

Generate a nested list of 0's and 1's by comparing two nested lists in python


I have two nested lists as below:

list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579], 
          [283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]

list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]

I would like to compare elements of the same index position in the above nested lists meaning list_x[0] should be compared with list_y[0] and so on.

I want to generate a third (nested) list such that for each number in list_x[0], if the number is also in list_y[0], a one is generated and if there is no match, a zero is generated. The same process should be executed for list_x[1] and list_y[1].

The length of each sub-list in my nested output list should be 10 (i.e. the length of the longer sub-list, a one where there is a match and a zero if there is no match). All the sub-lists are sorted in ascending order.

Some additional information worth sharing is that list_y[0] and list_y[1] are subsets of list_x[0] and list_x[1] respectively.

Therefore the output list that I am seeking should be as follows:

out = [[1,0,0,1,0,1,0,1,1,0], [0,1,1,1,1,1,0,0,0,0]]

I tried the following code but I'm getting some 10 extra zeros

list_x = [y for x in list_x for y in x] #to flatten list_x

result = []
for y in list_y:
    sublist = []
    for x in list_x:
        if x in y:
            sublist.append(1)
        else: 
            sublist.append(0)
    result.append(sublist)

The above code gives me the following:

result = [[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0]]

Thanks if you can help!


Solution

  • Thomas, welcome to SO!

    Try this:

    #!/usr/bin/env python2
    
    list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579],
              [283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]
    
    list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]
    
    answer=[]
    for ( index, inner_list ) in enumerate( list_x ):
      answer.append([])
    
      for ( inner_index, inner_value ) in enumerate(inner_list):
        answer[index].append(0)
        if inner_value in list_y[ index ]:
          answer[index][inner_index] = 1
    print answer