Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements of 2D array by slice in python

I want to set value of G[1][0],G[1][1]...G[1][100] and G[0][1],G[1][1]...G[100][1] to be 1

G = [[0]*101]*101
G[1][:] = 1
G[:][1] = 1

Than I got error,

...
G[1][:] = 1
TypeError: can only assign an iterable

how can I do this without Numpy?

like image 343
Spike Avatar asked Mar 11 '16 11:03

Spike


2 Answers

There are a few flaws here.

First: Iterator assignment

First of all, the left-hand side of your assignment yields an iterable, so you can't assign a scalar to that. Instead, the right-hand side (in your case 1) needs to be an iterable of equal length, e.g.:

G[0][:] = [0] * 101 # Warning: Copied code from question, still flawed

Second: List of list references

You initialize your list in-line. This is okay for a list of literals, but will fail for the second dimension, as it will hold 101 references to the same internal list. Changing one element in there will have effects on all other indices.

You want to initialize your list like this:

G = [[0] * 101 for x in range(102)]

Third: List slice / hard-copy

The next thing is, that the [:]-call creates a hard-copy of your list. So what happens here, is:

  • G[0][:] takes the first column of your 2d list and hard-copies it.
  • G[:][0] hard-copies the entire 2d list and then returns the first column of that.

You probably do not want to copy the entire list around all the time, losing its reference and making changes only to the copies.

Finally: What you want

Assuming your first dimension refers to columns and your second dimension refers to rows:

Set all elements of a column to 1:

G[0] = [1] * 101

Set all elements of a row to 1:

for i in range(102): G[i][0] = 1
like image 105
jbndlr Avatar answered Oct 08 '22 03:10

jbndlr


First of all the way you created the list is wrong

See this question and answer

Using loop:

import pprint
lst = [[0]*10 for n in range(10)]
for i in range(len(lst[0][:])): #Iterating over column of first row
    lst[0][i] = 1
for j in range(len(lst)): #Iterating over row of first column 
    lst[j][0] =1
pprint.pprint(lst)

Output:

[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
like image 35
The6thSense Avatar answered Oct 08 '22 02:10

The6thSense