Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2 Dimensional Arrays
#1
Ok so here is the idea:
I have a grid that is 50 x 50. I want to store information of every single grid in an 2D Array. This would have been an easy feat in other languages but in Python it seems a bit challenging.
How can I do that? Thank you for the help!
Reply
#2
What is a grid? In the context of your question it is a meaningless term. More details please.
Reply
#3
(Mar-21-2021, 05:33 PM)Prithak Wrote: Ok so here is the idea:
I have a grid that is 50 x 50. I want to store information of every single grid in an 2D Array. This would have been an easy feat in other languages but in Python it seems a bit challenging.
How can I do that? Thank you for the help!

Aight let's forget about the grid. This becomes a simple question:

How do I make a 2D Array and access it's value if I have i and j as it's element?
Reply
#4
Nested lists are simple, but you have to initialize them or handle resizing.

size = 5
grid = []
for row in range(size):
    grid.append([0] * size)

grid[2][1] = 7
grid[3][0] = 2

for row in grid:
    print(row)
Output:
[0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 7, 0, 0, 0] [2, 0, 0, 0, 0] [0, 0, 0, 0, 0]
Sometimes I prefer just using a dict with a complex number as a key. You can easily find neighbors of a particular cell by doing math on the complex number.

size = 5
grid = {}
grid[2 + 1j] = 7
grid[3 + 0j] = 2
for x in range(size):
    print(",".join([str(grid.get(x + y*1j, 0)) for y in range(size)]))
Output:
0,0,0,0,0 0,0,0,0,0 0,7,0,0,0 2,0,0,0,0 0,0,0,0,0
You could also use numpy arrays.
Reply
#5
A 2D array of what? Numbers? For that you might want to use numpy arrays. Misc objects? For that you would use a list of lists.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to quantize a 4 dimensional array? PythonNPC 2 1,579 Apr-23-2022, 04:34 PM
Last Post: Gribouillis
  How to create 2 dimensional variables in Python? plumberpy 5 1,792 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  Slicing a 2 dimensional array Scott 2 1,617 Jan-12-2022, 07:18 AM
Last Post: paul18fr
  Problem using two-dimensional interpolation. Result looks bad player1682 4 2,451 Oct-12-2021, 09:27 AM
Last Post: player1682
  Index data must be 1-dimensional : Classifier with sklearn Salma 0 4,264 Apr-01-2021, 03:22 PM
Last Post: Salma
  comparing 2 dimensional list glennford49 10 4,038 Mar-24-2020, 05:23 PM
Last Post: saikiran
  Python 2 dimensional array creations sharpe 1 1,940 Nov-24-2019, 10:33 AM
Last Post: ThomasL
  Python: Creating N Dimensional Grid jf451 0 2,300 Dec-06-2018, 10:53 PM
Last Post: jf451
  Get last tuple from two-dimensional array? Winfried 6 3,783 Aug-27-2018, 01:48 PM
Last Post: buran
  Sum only some values from a two-dimensional list bronfai 2 2,959 Feb-12-2018, 04:27 AM
Last Post: bronfai

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020