Reputation: 25
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
Upvotes: 2
Views: 677
Reputation: 494
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]
Upvotes: 0
Reputation: 107297
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]
Upvotes: 4
Reputation: 8437
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
Upvotes: 1