Using Python3.x, I have a piece of code which generates X with list of sub-lists in single quotes separated by commas...need to print lines Y with replaced values from X.
X = ['sequence, A, 1, 2, 3',
'sequence, B, 10, 20, 30',
'sequence, C, 100, 200, 300']
Y = ['VEQ','1','map','2','cap',]
Expected output
'VEQ','1','A','2','1'
'VEQ','1','B','2','10'
'VEQ','1','C','2','100'
Y[field3-map] replaced with X[field2], Y[field5-cap] replaced with X[field3], other fields of Y will remain same.
I have already tried to modify below reference code according to my requirement, but it didn't work.
# helper function to find elements
def find_sub_idx(test_list, repl_list, start = 0):
length = len(repl_list)
for idx in range(start, len(test_list)):
if test_list[idx : idx + length] == repl_list:
return idx, idx + length
# helper function to perform final task
def replace_sub(test_list, repl_list, new_list):
length = len(new_list)
idx = 0
for start, end in iter(lambda: find_sub_idx(test_list, repl_list, idx), None):
test_list[start : end] = new_list
idx = start + length
Here's something simple and memory efficient (due to lazy evaluation of map), I'm printing the results, hence only one copy of Y is needed and can be overwritten:
X = ['sequence, A, 1, 2, 3',
'sequence, B, 10, 20, 30',
'sequence, C, 100, 200, 300']
Y = ['VEQ','1','map','2','cap',]
retval = Y[:]
for x in map(lambda x: str.split(x, ','), X):
retval[2] = x[1]
retval[4] = x[2]
print(retval)
If you want to store the values somewhere, you'll need to have a separate copy of Y each time:
X = ['sequence, A, 1, 2, 3',
'sequence, B, 10, 20, 30',
'sequence, C, 100, 200, 300']
Y = ['VEQ','1','map','2','cap',]
my_list = []
for x in map(lambda x: str.split(x, ','), X):
retval = Y[:]
retval[2] = x[1]
retval[4] = x[2]
my_list.append(retval)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With