Alex
Alex

Reputation: 23

how to create 2d array in python if we know number of rows,and number of columns depends on some condition?

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?

Upvotes: 2

Views: 1711

Answers (3)

Alex Martelli
Alex Martelli

Reputation: 881675

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)]

Upvotes: 3

Jesse Aldridge
Jesse Aldridge

Reputation: 8149

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

Upvotes: 1

Hamish Grubijan
Hamish Grubijan

Reputation: 10820

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.

Upvotes: 1

Related Questions