Home > Software design >  Replacing items in a list with items from another list in python
Replacing items in a list with items from another list in python

Time:04-19

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]

list2 = [0,2,1,0,5]

Would it be possible to replace each 3 in list1 with a 0 from list2? If so, how would I go about doing this?

CodePudding user response:

You could create an iterator for list2, and then call next() to replace the next element in list1 that is equal to 3, while using a list comprehension.

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
list2 = [0,2,1,0,5]
l2 = iter(list2)

out = [i if i!=3 else next(l2) for i in list1]
print(out)

Output:

[0, 4, 1, 1, 0, 2, 1, 0, 4, 1, 0, 2, 5]

CodePudding user response:

We can use two pointers to keep track of list1 and list2. Then we replace each 3 in list1 with a value from list2 even it is not 0 until traversing to the end of any of the list.

list1 = [3, 4, 1, 1, 0, 3, 1, 0, 4, 3, 3, 2, 3]
list2 = [0, 0, 0, 0, 0]
x = 0
y = 0
while x < len(list1) and y < len(list2):
    if list1[x] == 3:
        list1[x] = list2[y]
        y  = 1
    x  = 1
print(list1)

Output:

[0, 4, 1, 1, 0, 0, 1, 0, 4, 0, 0, 2, 0]

CodePudding user response:

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
list2 = [0,2,1,0,5]
l1_num = 3 # number to be replaced in list 1
l2_num = 0 # number to be replaced in list 2
n = min(list1.count(l1_num),list2.count(l2_num))
for i in range(n):
    list1[list1.index(l1_num)] = l2_num
    list2[list2.index(l2_num)] = l1_num
#list1 = [0, 4, 1, 1, 0, 0, 1, 0, 4, 3, 3, 2, 3]
#list2 = [3, 2, 1, 3, 5]

CodePudding user response:

we can use for in and store our needed short list value out of the loop. like the following code will replace all 3 in list1 with zeros and all 0 in list2 with 3s in list1:

    list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
    list2 = [0,1,0,3,0]
    #shortlistval will be used to store short list desired value
    shortlistVal =1;#default val is just for declaration 
    for i1 in range(0, len(list1)):
        for i in range(0,len(list2)):
            if list1[i1] ==3 and list2[i] == 0:
                shortlistVal=list2[i]
                list2[i]=list1[i1]
        if list1[i1]==3:
            list1[i1]= shortlistVal
    print(list1)
    print(list2)

Output:

   [0, 4, 1, 1, 0, 0, 1, 0, 4, 0, 0, 2, 0]
   [3, 1, 3, 3, 3]

CodePudding user response:

Use two for loops and replace each 3 for 0 s in list 2.

list1 = [3,4,1,1,0,3,1,0,4,3,3,2,3]
list2 = [0,2,1,0,5]

for i in range(list2.count(0)):
    for x in list1:
        if x == 3: list1[list1.index(x)] = 0; break

print(list1)

output:

[0, 4, 1, 1, 0, 0, 1, 0, 4, 3, 3, 2, 3]
  • Related