سؤال

I have a list (list1) as follows:

[0, 1, 2]

I want to prepend each element to a 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):
    for line in list2:
        Finallist.append("|".join((str(list1[x]),line)))
    x+=1

This gives back 9 lines. What's wrong? I would expect each item to be added.

هل كانت مفيدة؟

المحلول 2

enumerate and zip will do the work:

list1 = [0, 1, 2]

data1 = ['Start|983471|String1|True\n',
 'Start|983472|String2|True\n',
 'Start|983473|String3|True\n']

for 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']

نصائح أخرى

The problem with your code is that you effectively have 2 loops, one that goes through x from 0 to the length of the list and another one that goes through each line in the list so it looks like:

for x in range(len(list1)):
    for line in list2:
        Finallist.append("|".join((str(list1[x]),line)))

So you will be appending every line, on each iteration through list1. You probably wanted something like:

for x in range(len(list1)):
    Finallist.append("|".join((str(list1[x]),list2[x])))

Here's how to do it more compactly with a list comprehension:

>>> list1 = [0, 1, 2]
>>> list2 = ['Start|983471|String1|True\n',
 'Start|983472|String2|True\n',
 'Start|983473|String3|True\n']
>>> ['{0}|{1}'.format(num, s) for num, s in zip(list1, list2)]
['0|Start|983471|String1|True\n', '1|Start|983472|String2|True\n', '2|Start|983473|String3|True\n']

I observe you are just using the index of each line, so instead you could use:

['{0}|{1}'.format(i, s) for i, s in enumerate(list2)]

don't use for loop .. .while loop is sufficient..

list1=['Start|983471|String1|True\n', 'Start|983472|String2|True\n', 'Start|983473|String3|True\n']
list2=['1','2','3']   
Finallist = []
x=0
while x < len(nk):
    Finallist.append(str(list2[x])+'|'+list1[x])
    x+=1
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top