randomly iterating through a 2d list in python

  • Last Update :
  • Techknowledgy :

Create an array with all possible pairs of coordinates, shuffle this and iterate through as normal.

import random
coords = [(x, y) for x in range(self.gridWidth) for y in range(self.gridHeight)
      random.shuffle(coords)
      for i, j in coords:
      if self.grid[i][j] != 'b':
      print i, j
      self.grid[i][j].colour = self.rand_Land_Picker()

You can consider 2D array as 1D array and randomly iterate through it.

def rand_Random(self):
   randomRange = range(self.gridWidth * self.gridHeight)
shuffle(randomRange)

for index in randomRange:
   i = index / self.gridWidth
j = index % self.gridWidth
if self.grid[i][j] != 'b':
   print i, j
self.grid[i][j].colour = self.rand_Land_Picker()

You can do something like:

randomRange = range(w * h)
shuffle(randomRange)

for n in randomRange:
   i = n / w
j = n % w

Even prettier, i and j, can be found in one statement:

i, j = divmod(n, w)

Suggestion : 2

To process 2-dimensional array, you typically use nested loops. The first loop iterates through the row number, the second loop runs through the elements inside of a row. For example, that's how you display two-dimensional numerical list on the screen line by line, separating the numbers with spaces:,This is how you can use 2 nested loops to calculate the sum of all the numbers in the 2-dimensional list:,Then fill with zeros all the elements above the main diagonal. To make this, for each row with the number i you need to assign a value to a[i][j] for j=i+1, ..., n-1. To do that, you need nested loops: ,Say, a program takes on input two-dimensional array in the form of n rows, each of which contains m numbers separated by spaces. How do you force the program to read it? An example of how you can do it:

1._
None
None
a = [
   [1, 2, 3],
   [4, 5, 6]
]
print(a[0])
print(a[1])
b = a[0]
print(b)
print(a[0][2])
a[0][1] = 7
print(a)
print(b)
b[2] = 9
print(a[0])
print(b)
1._
None
None
a = [
   [1, 2, 3, 4],
   [5, 6],
   [7, 8, 9]
]
for i in range(len(a)):
   for j in range(len(a[i])):
   print(a[i][j], end = ' ')
print()
1._
None
None
a = [
   [1, 2, 3, 4],
   [5, 6],
   [7, 8, 9]
]
for row in a:
   for elem in row:
   print(elem, end = ' ')
print()
1._
None
None
a = [
   [1, 2, 3],
   [4, 5, 6]
]
print(a[0])
print(a[1])
b = a[0]
print(b)
print(a[0][2])
a[0][1] = 7
print(a)
print(b)
b[2] = 9
print(a[0])
print(b)
3._
None

Naturally, to output a single line you can use method join():

for row in a:
   print(' '.join([str(elem) for elem in row]))
8._
None
1._
None
None
a = [
   [1, 2, 3, 4],
   [5, 6],
   [7, 8, 9]
]
s = 0
for i in range(len(a)):
   for j in range(len(a[i])):
   s += a[i][j]
print(s)
1._
None
None
a = [
   [1, 2, 3, 4],
   [5, 6],
   [7, 8, 9]
]
s = 0
for row in a:
   for elem in row:
   s += elem
print(s)

Suggestion : 3

What is the best way to iterate over two dimensional array? is for loop is the only way? can't we use while loop or do while loop? how about Iterator? I heard array implements Iterable interface in Java? And finally, does Java 8 change the way you loop over multi-dimensional array in Java? ,How to loop over two dimensional array in Java? Ex..., Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions ,What Every Java Developer Should know about Array (see here)


 for (int row = 0; row < board.length; row++) {
    for (int col = 0; col < board[row].length; col++) {
       board[row][col] = row * col;
    }
 }

Suggestion : 4

To walk through every element of a one-dimensional list, we use a for loop, that is: , For a two-dimensional list, in order to reference every element, we must use two nested loops. This gives us a counter variable for every column and every row in the matrix. , In the case of a list, our old-fashioned one-dimensional list looks like this: , For example, we might write a program using a two-dimensional list to draw a grayscale image.

In the case of a list, our old-fashioned one-dimensional list looks like this:

        myList = [0, 1, 2, 3]

And a two-dimensional list looks like this:

        myList = [
           [0, 1, 2, 3],
           [3, 2, 1, 0],
           [3, 5, 6, 1],
           [3, 8, 3, 4]
        ]

For our purposes, it is better to think of the two-dimensional list as a matrix. A matrix can be thought of as a grid of numbers, arranged in rows and columns, kind of like a bingo board. We might write the two-dimensional list out as follows to illustrate this point:

        myList = [
           [0, 1, 2, 3],
           [3, 2, 1, 0],
           [3, 5, 6, 1],
           [3, 8, 3, 4]
        ]


To walk through every element of a one-dimensional list, we use a for loop, that is:

 myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 for index in len(myList):
    myList[index] = 0 # Set element at "index"
 to 0.


For a two-dimensional list, in order to reference every element, we must use two nested loops. This gives us a counter variable for every column and every row in the matrix.

        myList = [
           [0, 1, 2]
           [3, 4, 5]
           [6, 7, 8]
        ]

        # Two nested loops allow us to visit every spot in a 2 D list.
        # For every column i, visit every row j.
        for i in len(myList):
           for j in len(myList[0]):
           myList[i][j] = 0