2016-03-08 63 views

回答

4

您可以在列表解析中使用zip()功能是什么:

>>> lst = [1,4,5,6,3,2,4,0] 
>>> [i*10+j for i,j in zip(lst[0::2],lst[1::2])] 
[14, 56, 32, 40] 

至于覆盖与奇数项的列表可以使用itertools.izip_longest(在python 3.X itertools.zip_longest)的更一般的方法:通过将0作为参数fillvalue

>>> lst=[1,4,5,6,3,2,4] 
>>> 
>>> from itertools import izip_longest 
>>> [i*10+j for i,j in izip_longest(lst[0::2],lst[1::2], fillvalue=0)] 
[14, 56, 32, 40] 
+0

如果列表中有奇数个元素,则缺少最后一个元素。我已经更正了下面的 – EduardoCMB

+0

@EduardoCMB确实只是更新了新的选择。 – Kasramvd

1

另一种解决方案,只是为了好玩

lst = [1,4,5,6,3,2,4,0] 
it = iter(lst) 
for i in it: 
    num = int(str(i) + str(next(it))) 
    print num 
+1

你也错过了列表的最后一个元素,其中有奇数个元素 – EduardoCMB

+0

的确,在这种情况下刚刚询问OP的期望 –

0
lst = [1,4,5,6,3,2,4,0,1] 
length = len(lst) 
newList = [i*10+j for i,j in zip(lst[::2],lst[1::2])] 
if length % 2 == 1: 
    newList.append(lst[-1]*10) 

print newList 

输出:

[14, 56, 32, 40, 10] 
相关问题