在python中混合两个列表的最快方法

时间:2012-09-29 01:45:30

标签: python list

我们有两个列表

l1 = [1, 2, 3]
l2 = [a, b, c, d, e, f, g...]

结果:

list = [1, a, 2, b, 3, c, d, e, f, g...] 

无法使用zip(),因为它会将结果缩短为最小的list。我还需要输出list而不是iterable

7 个答案:

答案 0 :(得分:10)

>>> l1 = [1,2,3]
>>> l2 = ['a','b','c','d','e','f','g']
>>> [i for i in itertools.chain(*itertools.izip_longest(l1,l2)) if i is not None]
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']

要允许None值包含在列表中,您可以使用以下修改:

>>> from itertools import chain, izip_longest
>>> l1 = [1, None, 2, 3]
>>> l2 = ['a','b','c','d','e','f','g']
>>> sentinel = object()
>>> [i
     for i in chain(*izip_longest(l1, l2, fillvalue=sentinel))
     if i is not sentinel]
[1, 'a', None, 'b', 2, 'c', 3, 'd', 'e', 'f', 'g']

答案 1 :(得分:7)

另一种可能性......

[y for x in izip_longest(l1, l2) for y in x if y is not None]

(当然,从itertools导入izip_longest后)

答案 2 :(得分:2)

最简单的方法是使用the itertools docs中给出的循环收件人:

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

可以这样使用:

>>> l1 = [1,2,3]
>>> l2 = ["a", "b", "c", "d", "e", "f", "g"]
>>> list(roundrobin(l1, l2))
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']

请注意,2.x需要在the 2.x docs中提供的roundrobin略有不同的版本。

这也避免了zip_longest()方法存在的问题,因为列表可以包含None而不会被删除。

答案 3 :(得分:1)

minLen = len(l1) if len(l1) < len(l2) else len(l2)
for i in range(0, minLen):
  list[2*i] = l1[i]
  list[2*i+1] = l2[i]
list[i*2+2:] = l1[i+1:] if len(l1) > len(l2) else l2[i+1:]

这不是一个简短的方法,但它删除了不必要的依赖。

更新: 这是@jsvk

建议的另一种方式
mixed = []
for i in range( len(min(l1, l2)) ):
  mixed.append(l1[i])
  mixed.append(l2[i])
list += max(l1, l2)[i+1:]

答案 4 :(得分:0)

如果您需要单个列表中的输出,而不是元组列表,请尝试此操作。

Out=[]
[(Out.extend(i) for i in (itertools.izip_longest(l1,l2))]
Out=filter(None, Out)

答案 5 :(得分:0)

我并不认为这是最好的方法,但我只想指出可以使用zip:

b = zip(l1, l2)
a = []
[a.extend(i) for i in b]
a.extend(max([l1, l2], key=len)[len(b):])

>>> a
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']

答案 6 :(得分:0)

>>> a = [1, 2, 3]
>>> b = list("abcdefg")
>>> [x for e in zip(a, b) for x in e] + b[len(a):]
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']