Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create 2D list from string with given length and width

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?

like image 413
DanielD Avatar asked Jan 28 '23 07:01

DanielD


2 Answers

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']]
like image 64
Eugene Yarmash Avatar answered Feb 11 '23 16:02

Eugene Yarmash


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)))
like image 36
jpp Avatar answered Feb 11 '23 15:02

jpp