python merge 3列表为1个列表

时间:2016-01-13 08:45:08

标签: python list merge

我想将3个列表合并到python中的单个列表中。 例如,我有三个列表:

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

最后想得到

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

a,b,c

有没有更快的方法来合并这3个列表? 这是我的代码

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])

4 个答案:

答案 0 :(得分:8)

import itertools as it

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

答案 1 :(得分:2)

var clickRunning = false;
function OpenSth(){
     if (clickRunning) return;
     clickRunning = true;

     yourFunc({
      /* do your stuff*/
     },500,  function () {
        clickRunning= false;
     });
}

输出: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]

答案 2 :(得分:1)

使用reduce是另一种选择:

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

答案 3 :(得分:0)

你可以这样做:

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

由于您要添加列表,合并列表将包含来自abc的所有值,但不包含正确的顺序。这就是我使用.sort()对列表进行排序的原因