如何交错两个不同长度的列表?

时间:2018-01-11 04:50:51

标签: python

我对Python很陌生,我仍然很难将语言本身用于我的程序。这就是我到目前为止所拥有的:

# Purpose: 'twolists' = takes 2 lists, & returns a new list containing
# alternating elements of lists. 
# Return = final_list
# Parameter = list1, list2

def twolists(list1, list2): # don't forget to return final_list
    alt_list = []
    a1 = len(list1)
    a2 = len(list2)

    for i in range(# ? ):
        # append one thing from list1 to alt_list - How?
        # append one thing from list2 to alt_list - How?

现在该程序应该产生如下输出:

outcome = twolists([ ], ['w', 'x', 'y', 'z'])
print(outcome)
['w', 'x', 'y', 'z']

outcome = twolists([0, 1], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x']

outcome = twolists([0, 1], ['w', 'x', 'y', 'z'])
print(outcome)
[0, 'w', 1, 'x', 'y', 'z']

outcome = twolists([0, 1, 2, 3], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x', 2, 3]

6 个答案:

答案 0 :(得分:6)

def twolists(list1, list2):
    newlist = []
    a1 = len(list1)
    a2 = len(list2)

    for i in range(max(a1, a2)):
        if i < a1:
            newlist.append(list1[i])
        if i < a2:
            newlist.append(list2[i])

    return newlist

答案 1 :(得分:5)

这使用来自itertoolszip_longest(它是标准库的一部分)来组成列表理解,以将两个列表中的项目交错为tuple,默认情况下使用{{1}填充值。

这也使用来自None的{​​{1}}来展平列表。

最后,它会过滤列表中的chain项:

itertools

或者按照@EliKorvigo的建议,使用None进行懒惰迭代:

from itertools import chain, zip_longest
def twolists(l1, l2):
    return [x for x in chain(*zip_longest(l1, l2)) if x is not None]
测试
itertools.chain.from_iterable

答案 2 :(得分:3)

基本方法:

您可以正常zip()列表,如果两个列表的大小不同,则附加最大列表的其余部分:

def two_lists(lst1, lst2):
    result = []

    for pair in zip(lst1, lst2):
        result.extend(pair)

    if len(lst1) != len(lst2):
        lsts = [lst1, lst2]
        smallest = min(lsts, key = len)
        biggest = max(lsts, key = len)
        rest = biggest[len(smallest):]
        result.extend(rest)

    return result

其工作原理如下:

>>> print(two_lists([], ['w', 'x', 'y', 'z']))
['w', 'x', 'y', 'z']
>>> print(two_lists([0, 1], ['w', 'x']))
[0, 'w', 1, 'x']
>>> print(two_lists([0, 1], ['w', 'x', 'y', 'z']))
[0, 'w', 1, 'x', 'y', 'z']
>>> print(two_lists([0, 1, 2, 3], ['w', 'x']))
[0, 'w', 1, 'x', 2, 3]

另一种可能的方法:

您也可以使用collections.deque预先将列表转换为deque()个对象,并使用popleft()弹出每个对象的开头,直到其中一个对象为空。然后你可以追加尚未为空的列表的其余部分。

以下是一个例子:

def two_lists2(lst1, lst2):
    result = []

    fst, snd = deque(lst1), deque(lst2)

    while fst and snd:
        result.append(fst.popleft())
        result.append(snd.popleft())

    rest = leftover(fst, snd)
    if rest:
        result.extend(rest)

    return result

def leftover(x, y):
    if x and not y:
        return x

    elif y and not x:
        return y

    return None

注意:这两种方法都是O(n)时间,这是这类问题的预期。

答案 3 :(得分:1)

def CombineLists(lst1, lst2):
   return [item for x in zip(lst1,lst2) for item in x] + /
         (lst2[len(lst1):] if len(lst2)>len(lst1) else lst1[len(lst2):])

答案 4 :(得分:-1)

这是一个处理迭代器的解决方案。这样做的好处是它可以与任何可迭代的数据结构一起使用,而不仅仅是列表。

def twolists(list1, list2):
    result = []
    iter1 = iter(list1)
    iter2 = iter(list2)
    try:
        while True:
            result.append(next(iter1))
            result.append(next(iter2))
    except StopIteration:
        # This exception will be raised when either of the iterators
        # hits the end of the sequence.
        pass
    # One of the lists is exhausted, but not both of them. We need
    # to finish exhausting the lists.
    try:
        while True:
            result.append(next(iter1))
    except StopIteration:
        pass
    try:
        while True:
            result.append(next(iter2))
    except StopIteration:
        pass
    return result

答案 5 :(得分:-1)

如果您不关心原始列表(以下示例中的ab)是否发生更改,则可以使用以下代码段:

def twolists(a, b):
    result = []
    while len(a) > 0:
        result.append(a.pop(0))
        if len(b) > 0:
            result.append(b.pop(0))
    result += a + b
    return result

twolists([ ], ['w', 'x', 'y', 'z'])
print(outcome)

outcome = twolists([0, 1], ['w', 'x'])
print(outcome)

outcome = twolists([0, 1], ['w', 'x', 'y', 'z'])
print(outcome)

outcome = twolists([0, 1, 2, 3], ['w', 'x'])
print(outcome)

产生以下输出:

['w', 'x', 'y', 'z']
[0, 'w', 1, 'x']
[0, 'w', 1, 'x', 'y', 'z']
[0, 'w', 1, 'x', 2, 3]