DanielD
DanielD

Reputation: 87

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?

Upvotes: 4

Views: 785

Answers (5)

kuzand
kuzand

Reputation: 9806

If you would like to use numpy arrays instead of 2D lists, you can do the following trick:

>>> s = '044010010A1A'

>>> np.array([s]).view('<U2').reshape(-1, 2)

array([['04', '40'],
       ['10', '01'],
       ['0A', '1A']], dtype='<U2')

This is much faster then using list comprehension proposed by Eugene Yarmash or itertools by jpp, and using numpy arrays instead of 2D lists has in general more advantages. However, if needed, you can convert a numpy array to list by the tolist() method.

Upvotes: 0

jpp
jpp

Reputation: 164843

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)))

Upvotes: 2

programmar
programmar

Reputation: 654

first: don't call your string str. It's already used by python.

import numpy as np
[list(l) for l in list(np.reshape(list(S),(int(len(S)/2),2)))]

numpy provides a fast function for reshaping list.

Upvotes: 0

A_kat
A_kat

Reputation: 1547

You should handle yourself what happens when there are even number of element on your string. Using textwrap saves you the trouble of parsing. It will create equal parts of the string, which in this case is 2

import textwrap
list = textwrap.wrap(str,2)
temp_list = []
for item in list:
  temp_list.append(item)
  if(len(temp_list)==2):
    list_2d.append(temp_list)
    temp_list = [] 

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 150188

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']]

Upvotes: 5

Related Questions