按两个列表中每个元素的顺序合并两个列表

时间:2015-12-15 21:07:26

标签: python list

我查看了以下question。我想在Python中做同样的事情。

  

列出a = [1,2,3 none,none]列表b = [4,5,3]输出= [1,4,2,5,3,3]

z = [ x for x in a if x != None ] + b

这不起作用。我希望z为[1,4,2,5,3,3]

3 个答案:

答案 0 :(得分:4)

from itertools import chain
list(chain.from_iterable(zip([1, 2, 3, None, None], [4, 5, 6])))
如上所述,

zip(a, b)会创建一个元组列表,chain.from_iterable将展开列表,放弃None s

答案 1 :(得分:2)

chainzip放在一起并删除None之后,您似乎希望from itertools import chain, izip_longest with_none = chain.from_iterable(izip_longest(a, b, fillvalue=None)] without_none = [x for x in with_none if x is not None] 列表...

extern "C" INT16 WINAPI SetWatchElements(INT16 *WatchElements)
{
INT16 Counter;

//some code

for (Counter = 0; Counter < WATCHSIZE; Counter++)
    WatchElements[Counter] = MAPINT(WatchData[Counter]);

//some code

return ReturnValue;
}

答案 2 :(得分:1)

使用zip(a, b),然后展开列表:

>>> [item for subtuple in zip(a, b) for item in subtuple]
[1, 4, 2, 5, 3, 3]