2

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を次のように表示したいと思います。

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

どうすればそれを達成できますか?

4

5 に答える 5

8

itertools.izip_longestを使用

from itertools import izip_longest
ListA = [b or a for a, b in izip_longest(ListA,ListB)]
于 2013-01-30T11:09:41.560 に答える
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'
于 2013-01-30T11:38:49.453 に答える
2

これを試して:

>>> [i[1] for i in map(None,ListA,ListB)]
['A', None, 'B', None, None]
于 2013-01-30T11:23:25.027 に答える
1

これを試して:

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

for x in range(len(ListB)): #till end of b
    ListA[x]=ListB[x]
于 2013-01-30T11:21:03.223 に答える
1

MAP を使用してリスト インデックスが範囲外エラーを回避する

for iterator,tup in enumerate(map(None,ListA,ListB)):
    if tup[1]:
        ListA[iterator] = tup[1]

これで問題は解決します。

于 2013-01-30T12:02:21.840 に答える