繁体   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