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

2024-09-30 10:39:26 发布

您现在位置: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?

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

^{pr2}$

Tags: tofrom程序lenaltonelistslist
3条回答

这将使用zip_longestfromitertools(这是标准库的一部分)来组合一个列表理解,将两个列表中的项交叉放入一个tuple,默认情况下使用None作为填充值。在

这还使用chain也来自itertools来展开列表。在

最后,它从列表中过滤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]

或者按照@EliKorvigo的建议,使用itertools.chain.from_iterable进行延迟迭代:

^{pr2}$ 测试
In [56]: twolists([0, 1], ['w', 'x'])
Out[56]: [0, 'w', 1, 'x']

In [57]: twolists([0, 1], ['w', 'x', 'y', 'z'])
Out[57]: [0, 'w', 1, 'x', 'y', 'z']

In [74]: twolists([0, 1, 2, 3], ['w', 'x'])
Out[74]: [0, 'w', 1, 'x', 2, 3]
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

基本方法:

您可以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

其工作原理如下:

^{pr2}$

另一种可能的方法:

您还可以使用^{}事先将列表转换为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)时间,这是此类问题的预期时间。在

相关问题 更多 >

    热门问题