如何从一位整数列表创建两位整数列表


l=[1,4,5,6,3,2,4,0]

我希望出来

成为
newlist=[14,56,32,40]

我试过了

for i in l[::2]:
   newlist.append(i)

怎么办

您可以在列表推导式中使用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]

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

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
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]

最新更新