4

2 つのリストが与えられた場合、最初のリストのすべての要素が偶数インデックス (順序を保持) し、2 番目のリストのすべての要素が奇数インデックス (順序も保持) になるようにそれらをマージします。以下の例:

x = [0,1,2]
y = [3,4]

result = [0,3,1,4,2]

for ループを使用して実行できます。しかし、これを行うための派手なpythonicな方法があると思います(あまり知られていない関数などを使用します)。forループを書くより良い解決策はありますか?

編集: リストの内包表記について考えていましたが、これまでのところ解決策は思いつきませんでした。

4

7 に答える 7

8

ここにあなたが使うことができるものがあります。( list(izip_longest(...))Py2xに使用)

>>> from itertools import chain
>>> from itertools import zip_longest
>>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = ''))))
[0, 3, 1, 4, 2]

これは、次のような任意の長さのリストで機能します-

>>> x = [0, 1, 2, 3, 4]
>>> y = [5, 6]
>>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = ''))))
[0, 5, 1, 6, 2, 3, 4]

動作についての説明-

  1. zip_longest(...)with a fill value は、リストを圧縮し、長さが等しくない iterable に対して指定された fill 値を埋めます。したがって、元の例では、次のように評価されます[(0, 3), (1, 4), (2, '')]
  2. このメソッドはタプルのリストを提供するため、結果を平坦化する必要があります。そのために、chain.from_iterable(...)のようなものを使用します[0, 3, 1, 4, 2, '']
  3. を使用filter(...)してすべての出現箇所を削除する''と、必要な答えが得られます。
于 2013-08-04T10:15:51.993 に答える
6

itertoolsroundrobin レシピを使用します。

from itertools import cycle, islice
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))
>>> list(roundrobin(x,y))
[0, 3, 1, 4, 2]
于 2013-08-04T10:18:32.480 に答える
5

これを試して:

x = [0,1,2,10,11]
y = [3,4]

n =  2*max([len(x),len(y)])
res = n *[None]
res[:2*len(x):2] = x
res[1:2*len(y):2] = y
res = [x for x in res if x!=None]
print res

不均等に長いリストでも機能するはずです。

于 2013-08-04T10:16:46.597 に答える
4

同じ長さのリストがある場合は、これを使用できます。

result = [ item for tup in zip(x,y) for item in tup ]
于 2013-11-24T13:34:47.970 に答える
2

スライスでできます。 端末で次のことcountを行います。slice

>>> list1=['Apple','Mango','Orange']
>>> list2=['One','Two','Three']
>>> list = [None]*(len(list1)+len(list2))
>>> list[::2] = list1
>>> list[1::2] = list2
>>> list

出力:

 ['Apple', 'One', 'Mango', 'Two', 'Orange', 'Three']
于 2015-03-03T09:41:33.227 に答える