How can I change the grouping of items in a list?
So, if I have a list like this:
x = [0,1,2,3,4,5,6,7,8,9]
How do I convert this list to something like this:
x = [01,23,45,67,89]
How can i do this?
I know about the inline function zip
, but I don't want tuple
and I want 2 numbers to be grouped into 1.
+3
Infinity Loop
source
to share
3 answers
You can try this:
x = [0,1,2,3,4,5,6,7,8,9]
x = map(str, x)
new_list = map(int, [x[i]+x[i+1] for i in range(0, len(x)-1, 2)])
+3
Ajax1234
source
to share
Using the concepts of zip and list, assuming the datatype is converted from a list of int to a list of strings:
In [1]: x = [0,1,2,3,4,5,6,7,8,9]
In [2]: pairs = zip(x[::2], x[1::2])
In [3]: pairs
Out[3]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
In [4]: [str(fst) + str(snd) for fst, snd in pairs]
Out[4]: ['01', '23', '45', '67', '89']
+2
THK
source
to share
It's much easier to understand and is one liner:
# l = list of string of items in list u with index(i) and index(i+1) and i increments by 2
l = [ str( u[i]) + str( u[i+1]) for i in range( 0, len(u), 2)]
+1
Siegfried winterstein
source
to share