3

I want to merge 3 lists in to a single list. For example, I have three lists:

a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]

and finally I want to get

merged = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

out of a, b, c

Are there any faster way to merge these 3 lists? Here's my code:

merged = []
a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
for i in range(0, len(a)):
    merged.append(a[i])
    merged.append(b[i])
    merged.append(c[i])
Georgy
  • 12,464
  • 7
  • 65
  • 73
신우석
  • 115
  • 1
  • 2
  • 8

4 Answers4

8
import itertools as it

list(it.chain.from_iterable(it.izip(a,b,c)))
eumiro
  • 207,213
  • 34
  • 299
  • 261
2
a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
d=[]
print [j  for i in zip(a,b,c) for j in i]

Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

vks
  • 67,027
  • 10
  • 91
  • 124
1

Using reduce is another option:

>>> a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
>>> reduce(lambda x, y: list(x)+list(y), zip(a,b, c))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • @Baruchel, zip is returning a list of tuples, so you need to wrap the values into a list before doing the add. – Netwave Jan 13 '16 at 08:53
0

You can do it like this:

a = [0, 3, 6, 9]
b = [1, 4, 7, 10]
c = [2, 5, 8, 11]
merged=a+b+c
merged.sort()

Since you are adding the list the merged list will contains all values from abc but not in the correct order.That's why I used .sort() to sort the list

cssGEEK
  • 994
  • 2
  • 15
  • 38