Python how to prepend element in list to another list of strings -
i have list (list1) follows:
[0, 1, 2]
i want prepend each element list (list2
) of strings:
['start|983471|string1|true\n', 'start|983472|string2|true\n', 'start|983473|string3|true\n']
to give:
['0|start|983471|string1|true\n', '1|start|983472|string2|true\n', '2|start|983473|string3|true\n']
my code:
finallist = [] x=0 while x < len(list1): line in list2: finallist.append("|".join((str(list1[x]),line))) x+=1
this gives 9 lines. what's wrong? expect each item added.
enumerate
, zip
work:
list1 = [0, 1, 2] data1 = ['start|983471|string1|true\n', 'start|983472|string2|true\n', 'start|983473|string3|true\n'] i, (line, num) in enumerate(zip(data1[:], list1)): data1[i] = str(num) + '|' + line print(data1)
output:
['0|start|983471|string1|true\n', '1|start|983472|string2|true\n', '2|start|983473|string3|true\n']
Comments
Post a Comment