Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

python - Merge 3 lists into 1 list

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])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import itertools as it

list(it.chain.from_iterable(it.izip(a,b,c)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...