简体   繁体   中英

Merge two lists in python to one

I need to merge two list onto one list and print it

for example:

list1 = [9, 3, 5, 7]
list2 = [5, 4 , 6]

list3 = [9, 5, 3, 4, 5, 6, 7]

I need to do it with "for" or "while" because we haven't learn something more advanced than that.

my code for now:

list1 = [3, 4, 5, 6]
list2 = [1, 2, 0, 9, 9]
tlist = []
n1 = len(list1)
n2 = len(list2)
n3 = n1 + n2
n4 = len(list2) - 1
n5 = len(list1) - 1
i = 1
c = 0
while i in range(0, n3):
    tlist.insert(i, list1[c])
    tlist.insert(i, list2[c])    
    c += 1
    i += 2
tlist.extend(list2[n4:])
tlist.extend(list1[n5:])
for num in tlist:
    print num

the result is:

3
1
4
2
5
0
6
9
9
6

(thats how it is supposed to be in the end) so I've manage to do it if len(list1) = len(list2) but if the list are in different length it's not working

Your code always appends the last element of each list, regardless of the list lengths. Instead, try this extension:

tlist.extend(list2[c+1:])
tlist.extend(list1[c+1:])

I get the expected output with this change: it starts from where the loop left off (c), instead of from the last element (n4, n5).

Also, your while loop bound is wrong; it works only if the two list lengths differ by no more than 1. Otherwise, you'll get a subscript out of range error. Try this:

for c in range(min(n1, n2)):
    tlist.insert(i, list1[c])
    tlist.insert(i, list2[c])
    i += 2
    # do not increment c; the for statement handles that part.

This quits the copying when either list runs out.

By the way, please change to meaningful variable names. The n1-n5 series tells us nothing about their purposes. 'c' and 'i' are also weak. Don't be afraid to type more.


Updated program, including lengthened test case:

list1 = [3, 4, 5, 6]
list2 = [1, 2, 0, 9, 8, 7, -1]
tlist = []
n1 = len(list1)
n2 = len(list2)
n4 = len(list2) - 1
n5 = len(list1) - 1
i = 1

for c in range(min(n1, n2)):
    tlist.insert(i, list1[c])
    tlist.insert(i, list2[c])
    i += 2
    print tlist

tlist.extend(list2[c+1:])
tlist.extend(list1[c+1:])

print tlist

simply add two lists using "+" to merge them.

In [1]: a = [1,2,3]

In [2]: b = [2,3]

In [3]: a+b
Out[3]: [1, 2, 3, 2, 3]

or you can do the following:

for i in b:
   ...:     a.append(i)
   ...:     

In [5]: a
Out[5]: [1, 2, 3, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM