My array maximum dimension could be 2x27,but number of columns could be lower than 27.Number of columns depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns or has more elegant way to do this?
views:
109answers:
4
+1
A:
For so few elements use a dictionary, with tuples as keys:
dct = {}
dct[(0,0)] = 'X'
if (10,10) in dct:
dct[(10,10)] += 1
else:
dct[(10,10] = 0
# Deleting a row / column
dct.pop((10,0))
dct.pop((10,1))
...
dct.pop((10,10))
Dictionaries are very flexible.
Alternatively use a numpy array.
Hamish Grubijan
2010-01-12 23:56:44
A:
Check this link about Numpy Array. This page has some simple examples of use.
Pedro Ghilardi
2010-01-13 00:01:13
+1
A:
Here is a simple way to handle it:
num_rows, num_cols = 2, 27
table = []
for r in range(num_rows):
row = []
table.append(row)
for c in range(num_cols):
row.append(c)
print table
Jesse Aldridge
2010-01-13 00:25:12
This is not bad unless you need to shrink / grow the bad boy. Really all depends on what the asker is trying to do.
Hamish Grubijan
2010-01-13 01:26:13
+3
A:
No, it makes no particular sense to build a larger array then remove some part of it -- just build what you need. Assuming that by "2d array" you actually mean "list of lists":
def makarray(value, nrows, ncols):
return [[value]*ncols for _ in range(nrows)]
Alex Martelli
2010-01-13 03:56:21
Ok, I feel stupid now :) Also, I think you might have gotten nrows and ncols backwards...
Jesse Aldridge
2010-01-13 05:30:17
@Jesse, you're right about the cols/rows (guess you can take the guy out of Fortran but you can't take Fortran out of the guy!-) -- editing now, thanks.
Alex Martelli
2010-01-13 06:46:02