在Python中合并两个不同大小的列表

2 投票
5 回答
2496 浏览
提问于 2025-04-17 14:10

当我尝试使用两个不同大小的列表时,出现了“列表索引超出范围”的错误。

举个例子:

ListA = [None, None, None, None, None]
ListB = ['A', None, 'B']

for x, y in enumerate(ListA):
    if ListB[x]:
        ListA[x]=ListB[x]

这样做会导致“列表索引超出范围”的错误,因为 ListB[3] 和 ListB[4] 这两个位置并不存在:
我希望把 ListA 和 ListB 合并,让 ListA 看起来像这样:

ListA = ['A', None, 'B', None, None]

我该怎么做才能实现这个呢?

相关问题:

5 个回答

2

试试这个:

>>> [i[1] for i in map(None,ListA,ListB)]
['A', None, 'B', None, None]
3

最快的解决办法是使用切片赋值

>>> ListA = [None, None, None, None, None]
>>> ListB = ['A', None, 'B']
>>> ListA[:len(ListB)] = ListB
>>> ListA
['A', None, 'B', None, None]

计时

>>> def merge_AO(ListA, ListB):
    return [ i[1] for i in map(None,ListA,ListB)]

>>> def merge_ke(ListA, ListB):
    for x in range(len(ListB)): #till end of b
        ListA[x]=ListB[x]
    return ListA

>>> def merge_JK(ListA, ListB):
    ListA = [b or a for a, b in izip_longest(ListA,ListB)]
    return ListA

>>> def merge_AB(ListA, ListB):
    ListA[:len(ListB)] = ListB
    return ListA

>>> funcs = ["merge_{}".format(e) for e in ["AO","ke","JK","AB"]]
>>> _setup = "from __main__ import izip_longest, ListA, ListB, {}"
>>> tit = [(timeit.Timer(stmt=f + "(ListA, ListB)", setup = _setup.format(f)), f) for f in funcs]
>>> for t, foo in tit:
    "{} took {} secs".format(t.timeit(100000), foo)


'0.259869612113 took merge_AO secs'
'0.115819095634 took merge_ke secs'
'0.204675467452 took merge_JK secs'
'0.0318886645255 took merge_AB secs'
8

使用 itertools.izip_longest

from itertools import izip_longest
ListA = [b or a for a, b in izip_longest(ListA,ListB)]

撰写回答