简体   繁体   中英

Create multi-dimensional list from list

I have attempted to search for an answer to this, but haven't found a good one yet. So I apologize in advance if the answer to this can be found somewhere else.

What is the Python way to do this?

height, width = 4, 4
grid = '01 02 03 04 04 03 02 01 04 04 04 04 01 02 01 02'
grid_list = []
grid = [int(x) for x in grid.split()]
for row in range(0, height):
    grid_list.append(grid[row * height:row * height + width])

I wish to make grid_list =[[1, 2, 3, 4], [4, 3, 2, 1], [4, 4, 4, 4], [1, 2, 1, 2]] .

Essentially, I want to create a multi-dimensional list from a string. I feel like there should be a Python one-liner for this. Thanks!

width = 4
string = '01 02 03 04 04 03 02 01 04 04 04 04 01 02 01 02'
grid = [int(x) for x in string.split()]
grid_list = [grid[i:i + width] for i in range(0, len(grid), width)]

After running this:

>>> grid_list
[[1, 2, 3, 4], [4, 3, 2, 1], [4, 4, 4, 4], [1, 2, 1, 2]]

Although you may not want to use Numpy, I'll put this out here. Otherwise you can look at 0605002's answer:

grid = '01 02 03 04 04 03 02 01 04 04 04 04 01 02 01 02'
grid = np.array([int(x) for x in grid.split()]).reshape((height, width))

If and only if all your element is same long (here two-letter), you could do it in one line in native Python method:

>>> width = 4
>>> grid = '01 02 03 04 04 03 02 01 04 04 04 04 01 02 01 02'
>>> [[int(x) for x in grid[i:i+width*3].split()] for i in xrange(0, len(grid), width*3)]
[[1, 2, 3, 4], [4, 3, 2, 1], [4, 4, 4, 4], [1, 2, 1, 2]]

If the elements has different lenght, the following one-line code might help:

>>> width = 4
>>> grid = '01 02 03 04 04 03 02 01 04 04 104 04 01 02 01 02'
>>> [[int(x) for x in grid.split()][i:i+width] for i in xrange(0, grid.count(" "), width)]
[[1, 2, 3, 4], [4, 3, 2, 1], [4, 4, 104, 4], [1, 2, 1, 2]]

Hope it be helpful!

If you allow to use numpy we can do like this too:

>>> grid = '01 02 03 04 04 03 02 01 04 04 04 04 01 02 01 02'
>>> gint = [int(x) for x in grid.split()]
>>> numpy.array(gint).reshape(4,4)
array([[1, 2, 3, 4],
   [4, 3, 2, 1],
   [4, 4, 4, 4],
   [1, 2, 1, 2]])
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM