Issue
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
.
Solution
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:]
Answered By - Grismar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.