简体   繁体   中英

How to create a double digit integer list from a single digit integer list?

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

I want the to out come to be

newlist=[14,56,32,40]

I have tried

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

what to do

You can use zip() function within a list comprehension:

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

As a more general approach for covering the list with odd number of items you can use itertools.izip_longest (in python 3.X itertools.zip_longest ) : by passing the 0 as fillvalue argument:

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

An alternate solution, just for fun

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

Output:

[14, 56, 32, 40, 10]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM