zingy
zingy

Reputation: 811

Replacing an item of a list by the item of another list if the condition matches

Suppose I have 2 lists as below. I am comparing items of both the lists and if the 1st item of list1 exists in the item of list2 then replace the item of list1 by the matched item of list2 and then delete that item from list2. Then it should move to the 2nd item of list1 and so on. I have the following code which is incorrect but I can't figure out the way. The number of items in both the lists may not be the same.

list1 = ["abc", "abc", "abc", "xyz", "xyz"]
list2= ["abc123", "abc456", "abc000", "xyz111"]

for i in list1:
    for j in list2:
        if i in j:
            i.replace(i, j)
            list2.remove(j)
            continue
        else:
            continue

The result should be as:

list1 = ["abc123", "abc456", "abc000", "xyz111", "xyz"]

Upvotes: 0

Views: 186

Answers (4)

user3273866
user3273866

Reputation: 604

Here is code:

>>> for list in list1:
...     for a in list2:
...         if list in a:
...             list1[list1.index(list)] = a
...             del list2[list2.index(a)]
... 
>>> 
>>> print list1
['abc123', 'abc000', 'abc456', 'xyz111', 'xyz']
>>> print list2
[]
>>> 

Upvotes: 1

Vor
Vor

Reputation: 35109

Here is another solution:

>>> list1 = ["abc", "abc", "abc", "xyz", "xyz"]
>>> list2= ["abc123", "abc456", "abc000", "xyz111"]
>>>
>>> [ list2[i] if i < len(list2) and list2[i].startswith(elem) 
...   else elem
...   for i, elem in enumerate(list1)]

Output:

['abc123', 'abc456', 'abc000', 'xyz111', 'xyz']

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 121975

I would use list comprehension and [i]zip_longest for this:

from itertools import izip_longest # zip_longest for 3.x

list1 = [b if a in b else a 
         for a, b in izip_longest(list1, list2, fillvalue="")]
list2 = [a for a in list2 if a not in list1]

This keeps the indexing consistent between the two lists during the first step (unlike remove), then clears out list2 afterwards.

Upvotes: 4

kaslusimoes
kaslusimoes

Reputation: 235

When you do for i in list1, you are getting the elements of the list, not the position of the list.

>>> for i in list1:
...    print(type(i))
... 
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

To work correctly you should do something like this down here and change the list inplace

>>> for i in range(len(list1)):
...    print(i)
... 
0
1
2
3
4

Upvotes: 1

Related Questions