Home > Back-end >  Merging two list with certain condition
Merging two list with certain condition

Time:09-21

I have listA = [2,0,0,5,6,0] and listB = [4,5,7,3,2,1]. I want to merge these two list and get listC = [2,5,7,5,6,1]. So basically just copy listA but if an element in listA is zero, replace that element with element from listB

I tried using for and if loop but had no luck:

listC = []
for i in listA and listB:
    if listA[i] == 0: 
        listC.append(listB[i])
    else:
        listC.append(listA[i])

I am new to python, so some explanation with solutions will be appreciated.

CodePudding user response:

You want to loop over the indices, not the elements of the list.
So what we need here is for i in range(len(listA)).
We can break this expression further to get a better understanding:

  • len(listA) gives the number of elements in list A. Clearly, this solution will only work if listA and listB have the same number of elements. In your example, len(listA) equals 5

  • range(len(listA)) will iterate over a range of integers: from 0 to len(listA) - 1. For our running example, this will be range(5), so from 0 to 4

  • for i in range(len(listA)) then just loops over i = [0, 1, 2, 3, 4].

listA = [2,0,0,5,6,0]
listB = [4,5,7,3,2,1]
listC = []

for i in range(len(listA)):
    if listA[i] == 0:
        listC.append(listB[i])
    else:
        listC.append(listA[i])

print(listC) # [2, 5, 7, 5, 6, 1]

I'll leave a couple of one-liners you can come back to once you are farther ahead in your python journey.

  • listC = [b if a == 0 else a for (a, b) in zip(listA, listB)]

  • list(map(lambda ab: ab[1] if ab[0] == 0 else ab[0], zip(listA, listB)))

Good luck!

CodePudding user response:

(Because you say new in python, I send for you another approach maybe helps you.)

You can use enumerate. With enumerate you can iterate over index and value in listA and when value of listA == 0 you can with index go to listB and get value in listB and insert value in listA.

listA = [2,0,0,5,6,0] 
listB = [4,5,7,3,2,1]

for index, value in enumerate(listA):
    if listA[index] == 0:
        listA[index] = listB[index]
        
print(listA)

Output:

[2, 5, 7, 5, 6, 1]

CodePudding user response:

Your main issue is that you are iterating over the elements of listB rather than the indexes, so when you you are indexing the lists you are not pulling the right values. There are two options here.

The simplest is to simply iterate over the indexes rather than the elements:

for i in range(len(listA)):
    if listA[i] == 0: 
        listC.append(listB[i])
    else:
        listC.append(listA[i])

If you can assume both lists will always been of the same length you can leverage zip to iterate over the elements of both lists at the same time:

for a, b in zip(istA, listb):
    if a == 0:
        listC.append(b)
    else:
        listC.append(a)

or more simply as a list comprehension:

[b if a == 0 else a for a, b in zip(listA, listB)]
  • Related