簡體   English   中英

從第一個列表中獲取第一個項目,從第二個列表中獲取最后一個項目來創建新列表

[英]Create new list by taking first item from first list, and last item from second list

如何循環瀏覽我的2個列表以便我可以使用

a=[1,2,3,8,12]
b=[2,6,4,5,6]

要得到

[1,6,2,5,3,8,6,12,2]

或使用

d=[a,b,c,d]
e=[w,x,y,z]

要得到

[a,z,b,y,c,x,d,w]

(第1個列表中的第1個元素,第2個列表中的最后元素)
(第1列表中的第2個元素,第2個列表中的第2個元素)

[value for pair in zip(a, b[::-1]) for value in pair]

您可以壓縮第一列表與第二個(使用的反向itertools.izip_longest ),然后使用連接列itertools.chain

>>> d=['a','b','c','d']
>>> e=['w','x','y','z']
>>> 
>>> from itertools import chain, zip_longest # in python 2 use izip_longest
>>> 
>>> list(chain(*izip_longest(d, e[::-1])))
['a', 'z', 'b', 'y', 'c', 'x', 'd', 'w']

使用zip_longest()的優點是它需要一個fillvalue參數,當列表的長度不相等時,該參數將被傳遞以填充省略的項目。

如果您確定列表的長度相等,則最好使用內置函數zip()

>>> d=['a','b']
>>> e=['w','x','y','z']
>>> list(chain(*izip_longest(d, e[::-1], fillvalue='')))
['a', 'z', 'b', 'y', '', 'x', '', 'w']

@Jon Clements建議的更多pythonic方式:

list(chain.from_iterable(zip_longest(d, reversed(e))))

好吧,我已經為python2做了一些測試:

import time
from operator import itemgetter
from itertools import chain, izip_longest

a = [1, 2, 3, 8, 12]
b = [2, 6, 4, 5, 6]

print "Using value and zip"
starttime = time.time()
c = [value for pair in zip(a, b[::-1]) for value in pair]
elapsed = time.time() - starttime
print c
print elapsed

print "Using chain and izip"
starttime = time.time()
c = list(chain(*izip_longest(a, b[::-1])))
elapsed = time.time() - starttime
print c
print elapsed

print "Using itemgetter"
c = []
starttime = time.time()
for i in xrange(0, len(a)):
    c.append(itemgetter(i)(a))
    c.append(itemgetter(len(b)-i-1)(b))
elapsed = time.time() - starttime
print c
print elapsed

輸出:

Using value and zip
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]
1.59740447998e-05
Using chain and izip
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]
3.2901763916e-05
Using itemgetter
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]
1.4066696167e-05

有時第一種方法更快,有時第三種方法更快。

這些是列表lenght = 1000的結果:

Using value and zip
0.000767946243286
Using chain and izip
0.000431060791016
Using itemgetter
0.00203609466553

正如您所看到的,第二種方法對於更長的列表變得更好。

這個怎么樣:

a=[1,2,3,8,12]
b=[2,6,4,5,6]
>>> a1 = list(map(lambda x: a1.extend([x,0]), a))
[None, None, None, None, None]
>>> a1
[1, 0, 2, 0, 3, 0, 8, 0, 12, 0]
>>> b1 = list(map(lambda x: b1.extend([0,x]), b[::-1]))
[None, None, None, None, None]
>>> b1
[0, 6, 0, 5, 0, 4, 0, 6, 0, 2]
>>> c = [x+y for x,y in zip(a1,b1)]
>>> c
[1, 6, 2, 5, 3, 4, 8, 6, 12, 2]

如果a和b的長度不同,則:

>>> c = [x+y for x,y in izip_longest(a1,b1)] #you choose your fillvalue.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM