Home > database >  Set rows in Python 2D array to another row without Numpy?
Set rows in Python 2D array to another row without Numpy?

Time:08-31

I want to "set" the values of a row of a Python nested list to another row without using NumPy.

I have a sample list:

lst = [[0, 0, 1],
       [0, 2, 3],
       [5, 2, 3]]

I want to make row 1 to row 2, row 2 to row 3, and row 3 to row 1. My desired output is:

lst = [[0, 2, 3],
       [5, 2, 3],
       [0, 0, 1]]

How can I do this without using Numpy?

I tried to do something like arr[[0, 1]] = arr[[1, 0]] but it gives the error 'NoneType' object is not subscriptable.

CodePudding user response:

One very straightforward way:

arr = [arr[-1], *arr[:-1]]

Or another way to achieve the same:

arr = [arr[-1]]   arr[:-1]

arr[-1] is the last element of the array. And arr[:-1] is everything up to the last element of the array.

The first solution builds a new list and adds the last element first and then all the other elements. The second one constructs a list with only the last element and then extends it with the list containing the rest.

Note: naming your list an array doesn't make it one. Although you can access a list of lists like arr[i1][i2], it's still just a list of lists. Look at the array documentation for Python's actual array.

The solution user @MadPhysicist provided comes down to the second solution provided here, since [arr[-1]] == arr[-1:]

CodePudding user response:

Since python does not actually support multidimensional lists, your task becomes simpler by virtue of the fact that you are dealing with a list containing lists of rows.

To roll the list, just reassemble the outer container:

result = lst[-1:]   lst[:-1]

Numpy has a special interpretation for lists of integers, like [0, 1], tuples, like :, -1, single integers, and slices. Python lists only understand single integers and slices as indices, and do not accept tuples as multidimensional indices, because, again, lists are fundamentally one-dimensional.

CodePudding user response:

use this generalisation

arr = [arr[-1]]   arr[:-1]

which according to your example means

arr[0],arr[1],arr[2] = arr[1],arr[2],arr[0]

or

arr = [arr[2]] arr[:2]

or

arr = [arr[2]] arr[:-1]

CodePudding user response:

You can use this

>>> lst = [[0, 0, 1],
       [0, 2, 3],
       [5, 2, 3]]
>>> lst = [*lst[1:], *lst[:1]]
>>>lst
 [[0, 2, 3],
   [5, 2, 3],
   [0, 0, 1]]
  • Related