How to create 2D list from string with n-rows and 2 cols?
Example:
str = "044010010A1A..."
list_2d = [['04','40'],
['10','01'],
['0A','1A']]...
Anyone can help?
You can use a list comprehension:
>>> s = '044010010A1A'
>>> [[s[i:i+2], s[i+2:i+4]] for i in range(0, len(s), 4)]
[['04', '40'], ['10', '01'], ['0A', '1A']]
You can use more_itertools.sliced
twice:
from more_itertools import sliced
s = '044010010A1A'
res = list(sliced(list(sliced(s, 2)), 2))
[['04', '40'], ['10', '01'], ['0A', '1A']]
If you don't want the 3rd party import, you can define sliced
yourself:
from itertools import count, takewhile
def sliced(seq, n):
return takewhile(bool, (seq[i: i + n] for i in count(0, n)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With