开发者

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 开发者_Go百科depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns or has more elegant way to do this?


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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜