I think that's what you want
nodes = [[Node() for j in range(cols)] for i in range(rows)]
But it is not always a good practice to initialize lists. For matrices it may make sense.
If you're wondering: Documentation about list comprehensions
Demo code:
>>> class Node:
def __repr__(self):
return "Node: %s" % id(self)
>>> cols = 3
>>> rows = 4
>>> nodes = [[Node() for j in range(cols)] for i in range(rows)]
>>> from pprint import pprint
>>> pprint(nodes)
[[Node: 41596976, Node: 41597048, Node: 41596904],
[Node: 41597120, Node: 41597192, Node: 41597336],
[Node: 41597552, Node: 41597624, Node: 41597696],
[Node: 41597768, Node: 41597840, Node: 41597912]]
Answer from JBernardo on Stack Overflow2D array of objects in Python - Stack Overflow
2D NumPy array of objects vs. 2D Python list efficiency
class - Making a 2d list of objects (Python 2.7) - Stack Overflow
2D list help in Python
I think that's what you want
nodes = [[Node() for j in range(cols)] for i in range(rows)]
But it is not always a good practice to initialize lists. For matrices it may make sense.
If you're wondering: Documentation about list comprehensions
Demo code:
>>> class Node:
def __repr__(self):
return "Node: %s" % id(self)
>>> cols = 3
>>> rows = 4
>>> nodes = [[Node() for j in range(cols)] for i in range(rows)]
>>> from pprint import pprint
>>> pprint(nodes)
[[Node: 41596976, Node: 41597048, Node: 41596904],
[Node: 41597120, Node: 41597192, Node: 41597336],
[Node: 41597552, Node: 41597624, Node: 41597696],
[Node: 41597768, Node: 41597840, Node: 41597912]]
Python doesnt really do 2d arrays. Here is a better explenation
Its does lists instead
I'm a little lost on this one, heres the function requirements:
def matrixes_add(a, b):
"""
-------------------------------------------------------
Sums the contents of matrixes a and b. a and b must have
the same number of rows and columns.
a and b must be unchanged.
Use: c = matrixes_add(a, b)
-------------------------------------------------------
Parameters:
a - a 2D list (2D list of int/float)
b - a 2D list (2D list of int/float)
Returns:
c - the matrix sum of a and b (2D list of int/float)
-------------------------------------------------------
"""Heres an example test and output:
matrixes_add([[0, 1], [2, 3], [4, 5]], [[6, 7], [8, 9], [1, 0]])
--> [[6, 8], [10, 12], [5, 5]]
Heres my code:
assert len(a) == len(b) and len(a[0]) == len(b[0])
c = []
sub_c = []
for i in range(len(a) - 1):
for j in range(len(a[i])):
sub_c.append(a[i][j] + b[i][j])
c.append(sub_c)
sub_c.clear()
return cwith the same list as the example i keep getting:
[[], []]
Any suggestions???
I have a rather simple question but I haven't been able to find an answer so far: if I have a 2D list of objects, how can I extract all the values from a common attribute?
This is some class:
class Foo():
def __init__(self, attr):
self.attr = attrFor a 1D list, it's really simple:
array = [Foo(i) for i in range(6)] [obj.attr for obj in array]
This will display: [0, 1, 2, 3, 4, 5].
For a multidimensional list, though, this won't work. A solution would be using loops or lists of comprehension to extract the attributes from each column or line. However, slices allow us to access a specific region of a multidimensional list.
So, let's say you have a 6x6 list (or ndarray) of objects, and you want to access the attributes at [4:,4:], or even better, you want to slice the list in a non-contiguous way and then get the attributes of all object elements in the pattern. Is that possible?
Check this image from the numpy docs to have a visual reference about what I'm talking about (see 2nd and 4th slices).
I'm aiming at being able to use this for a board game in which the board would be sliced into different "tile" groups or patterns and then check the properties of the objects in those tiles.
This is not homework.
If you want to do that you need to create a 'row' in the first loop to add into the main grid array. You then append cells to this row, and append the whole row to the grid.
Like so:
def insertion (r, c, grid):
cellGrid = []
for x in range(0, r):
row = []
for y in range(0, c):
if (grid[x][y] == '%'):
what = 0
cost = 100000000
elif(grid[x][y] == '-'):
what = 1
cost = 1
elif (grid[x][y] == '.'):
what = 2
cost = 0
else:
what = 3
row.append(Cell(what, cost))
cellGrid.append(row)
return cellGrid
Use list comprehensions to create a list of lists full of Nones. Change cellGrid initialization to:
cellGrid = [ [None for i in range(c)] for j in range(r)]
then you do
cellGrid[x][y] = Cell(what,cost)
Full code example:
def insertion (r, c, grid):
cellGrid = [ [None for i in range(c)] for j in range(r)]
for x in range(0, r):
for y in range(0, c):
if (grid[x][y] == '%'):
what = 0
cost = 100000000
elif(grid[x][y] == '-'):
what = 1
cost = 1
elif (grid[x][y] == '.'):
what = 2
cost = 0
else:
what = 3
cellGrid[x][y] = Cell(what,cost)
return cellGrid
To initialize a two-dimensional list in Python, use
t = [ [0]*3 for i in range(3)]
But don't use [[v]*n]*n, it is a trap!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
A pattern that often came up in Python was
bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)
which helped motivate the introduction of list comprehensions, which convert that snippet to
bar = [SOME_EXPRESSION for item in some_iterable]
which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.
Your code follows this pattern twice
twod_list = [] \
for i in range (0, 10): \
new = [] \ can be replaced } this too
for j in range (0, 10): } with a list /
new.append(foo) / comprehension /
twod_list.append(new) /
Hi redditors!
I'm learning Python and I have to do a project with 2D lists. I'm fairly new to programming and I'm having a hard time understanding the format of a 2D list.
I'm trying to create rows and columns with '.' but I can only print out one row.....can someone help me by giving a simple example on how to do 2D lists, please? Oh, and reddit is my last resource. I have been looking for material I can understand but I'm having trouble :_(