Home > Mobile >  how do you replace multiple strings in a list using loop for python?
how do you replace multiple strings in a list using loop for python?

Time:11-18

I would like to replace elements of a list b for elements from another list a

#my list is
b = [('ba'),
 ('bb'),
 ('bc'),
 ('bd'),
 ('be'),
 ('bf'),
 ('bg'),
 ('bh'),
 ('bi')]

#The second list
a = [('bc_1'),
 ('bd_1'),
 ('be_1'),
 ('bf_1'),
 ('bg_1')]

I would like to replace 'bc', 'bd', 'be', 'bf', 'bg' with 'bc_1', 'bd_1', 'be_1', 'bf_1', 'bg_1'

I tried with the next code

for i in a:
    if i in b:
      a = a.str.replace(i) 

but it does not work

CodePudding user response:

IIUC you want to replace the values in a if the part before the _ matches.

An efficient solution to avoid constantly looping over the values of a is to first build a dictionary to perform the match.

Then use a simple list comprehension.

a2 = {e.split('_')[0]: e for e in a}
output = [a2.get(e, e) for e in b]

output: ['ba', 'bb', 'bc_1', 'bd_1', 'be_1', 'bf_1', 'bg_1', 'bh', 'bi']

This solution will be much faster, especially on large datasets, as the indexing in dictionaries is O(1) due to the hashing of the keys.

content of a2:

{'bc': 'bc_1', 'bd': 'bd_1', 'be': 'be_1', 'bf': 'bf_1', 'bg': 'bg_1'}

CodePudding user response:

Try this:

output = []
for j in b:
    for i in a:
        if i.startswith(f"{j}_"):
            output.append(i)
            break
    else:  
        output.append(j)

then

>>> output
['ba', 'bb', 'bc_1', 'bd_1', 'be_1', 'bf_1', 'bg_1', 'bh', 'bi']

CodePudding user response:

Compare two letters of b and two letter of a to see if they are the same

for index, a_value in enumerate(b):
    for b_value in a:
        if a_value[0] == b_value[0] and a_value[1] == b_value[1]:
            b_value[index] = a_value

output :

b = ['ba', 'bb', 'bc_1', 'bd_1', 'be_1', 'bf_1', 'bg_1', 'bh', 'bi']
  • the number of comparison targets changes
for index, b_value in enumerate(b):
    length = len(b_value)
    for a_value in a:
        count = 0
        for k in range(length):
            if b_value[k] == a_value[k]:
                count  = 1
            else:
                break
            if count == length:
                b[index] = a_value

CodePudding user response:

for i in range(len(b)):
    for j in range(len(a)):
        if b[i] in a[j]:
            b[i]=a[j]

This should do the job for you. Currently your elements in the list are integers. But if your elements in the list are tuple then this wont work because tuple does not support item assignment. You will have to convert b and a to list of lists like so a = [['bc_1'],['bd_1']] etc. Then the below code will work.

for i in range(len(b)):
    for j in range(len(a)):
        if b[i][0] in a[j][0]:
            b[i][0]=a[j][0]

CodePudding user response:

try this :

for i in range(len(a)):
     a[i],b[i]=b[i],a[i]

output : ['bc_1', 'bd_1', 'be_1', 'bf_1', 'bg_1', 'bf', 'bg', 'bh', 'bi']

  • Related