在Python中加入2个不同大小的列表
当尝试使用2个不同大小的列表时,出现“索引列表超出范围”错误 例如:在Python中加入2个不同大小的列表,python,Python,当尝试使用2个不同大小的列表时,出现“索引列表超出范围”错误 例如: 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看起来像这样: Li
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]
我如何才能做到这一点?使用
试试这个:
ListA = [None, None, None, None, None]
ListB = ['A', None, 'B']
for x in range(len(ListB)): #till end of b
ListA[x]=ListB[x]
试试这个:
>>> [i[1] for i in map(None,ListA,ListB)]
['A', None, 'B', None, None]
最快的解决方案是使用切片分配
>>> 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'
使用映射避免列表索引超出范围错误
for iterator,tup in enumerate(map(None,ListA,ListB)):
if tup[1]:
ListA[iterator] = tup[1]
这将解决问题。注意,在这种特殊情况下,可以通过
listA=listB+listA[len(listB):]
或listA[:len(listB)]=listB
来实现结果。我认为这在python3.x上失败(不幸的是),因为map
的行为随着多个iterables的改变——特别是在python2.x上,map
使用较长的iterables,另一个用None
填充,而在python3.x上,map
使用两个iterables中较短的一个。
for iterator,tup in enumerate(map(None,ListA,ListB)):
if tup[1]:
ListA[iterator] = tup[1]