Home > Mobile >  split a string and concatenate values from a list
split a string and concatenate values from a list

Time:07-01

lstA looks like this:

["y1","y2","y3"]

and lstB looks like this:

["xx5, folder, 20-1-1", "xx6, appPath, 20-1-1", "xx7, Resolve, 23-1-4"]

All items are strings. Lengths of the lists are the same.

I want to iterate through each item of lstB and replace the first item before , with the element from lstA respectively.

At the end, lstB should look like this:

["y1, folder, 20-1-1", "y2, appPath, 20-1-1", "y3, Resolve, 23-1-4"]

First, I can iterate through lstB, split the string by , to obtain the value of the first item (for example "xx5"). Then, I can replace this with the respective element in lstA. However, I am not sure how I can replace since lstA is separate.

for i in lstB:
    toBeReplaced = i.split(',')[0]
    totalName = i.replace(toBeReplaced, lstA[i])

CodePudding user response:

very simplified method if you're new to programming.

  • code:
a = ["y1","y2","y3"]
b = ["xx5, folder, 20-1-1", "xx6, appPath, 20-1-1", "xx7, Resolve, 23-1-4"]
List = []
for i in range(len(a)):
    temp = b[i].split(',')
    temp[0] = a[i]
    List.append((',').join(temp))
  • output: ['y1, folder, 20-1-1', 'y2, appPath, 20-1-1', 'y3, Resolve, 23-1-4']

CodePudding user response:

Split and join the items of both list, can be done in a short list comprehension:

lstA = ["y1","y2","y3"]
lstB = ["xx5, folder, 20-1-1", "xx6, appPath, 20-1-1", "xx7, Resolve, 23-1-4"]

lstB = [','.join((a, *b.split(',')[1:])) for a, b in zip(lstA, lstB)]

CodePudding user response:

You can traverse the second list with an index variable i and replace the 3 first characters with the corresponding value from first list with [:] string slicing operator:

l = ["y1","y2","y3"]
l1 = ["xx5, folder, 20-1-1", "xx6, appPath, 20-1-1", "xx7, Resolve, 23-1-4"]

for i in range(len(l1)):
    l1[i] = (l[i]   l1[i][3:])
print(l1)

Output:

['y1, folder, 20-1-1', 'y2, appPath, 20-1-1', 'y3, Resolve, 23-1-4']

CodePudding user response:

Can be easily achieved using zip

a=["y1","y2","y3"]
b=["xx5, folder, 20-1-1", "xx6, appPath, 20-1-1", "xx7, Resolve, 23-1-4"]
print(b)
for i,(a_,b_) in enumerate(zip(a,b)):
    b[i]=b_.replace(b_.split(",")[0], a_)
print(b)

Output:

before=['xx5, folder, 20-1-1', 'xx6, appPath, 20-1-1', 'xx7, Resolve, 23-1-4']
after=['y1, folder, 20-1-1', 'y2, appPath, 20-1-1', 'y3, Resolve, 23-1-4']

CodePudding user response:

construct the new list using list comprehension

  1. zip the 2 lists and iterate over them.
  2. use split() at , and limit the maxsplit=1
  3. use f-string to create the new elements

code:

spam = ["y1","y2","y3"]
eggs = ["xx5, folder, 20-1-1", "xx6, appPath, 20-1-1", "xx7, Resolve, 23-1-4"]
print([f'{item1}, {item2.split(",", maxsplit=1)[-1]}' for item1, item2 in zip(spam, eggs)])

output

['y1,  folder, 20-1-1', 'y2,  appPath, 20-1-1', 'y3,  Resolve, 23-1-4']
  • Related