For example
l = [1, 2, 3, 4, 5, 6, 7, 8]
How would I get it to:
l = [12, 34, 56, 78]
For example
l = [1, 2, 3, 4, 5, 6, 7, 8]
How would I get it to:
l = [12, 34, 56, 78]
Using zip, you can combine elements together.
>>> l = [1,2,3,4,5,6,7,8]
>>> temp = list(zip(l[::2],l[1::2]))
# [(1, 2), (3, 4), (5, 6), (7, 8)]
Now combine them using list comprehension.
>>> out = [a*10+b for a,b in temp]
>>> out
=> [12, 34, 56, 78]
A crude method may be, but here you go -
l = [1,2,3,4,5,6,7,8]
[ int(str(l[a])+str(l[a+1])) for a in range(0,len(l),2) ]
1. range(0,len(l),2) ] is iterating over every other element
l[a] and l[a+1] are getting converted to string, concatenated
The output is getting casted back to int
Finally the whole logic is done in a list comprehension in a one-liner. Hope that helps!
Pretty spot-on answers, mine is similar, but here goes. Either of these one-liners will work:
way1 = [first*10 + nxt for first, nxt in zip(l[::2], l[1::2])]
way2 = [int(str(first) + str(nxt)) for first, nxt in zip(l[::2], l[1::2])]
In general you can do this:
general_way = [elems for elems in zip(l[::2], l[1::2])]
print(general_way)
[(1, 2), (3, 4), (5, 6), (7, 8)] # general_way
For those reading and new to python:
a_list[starting index: ending index: stepping] --for elem1, elem2, ..., elemN in zip(iterable1, iterable2, ...., iterableN): --It is recommended that all iterables be of equal length when using zip().