1
hhrmatata 2013-06-01 09:02:08 +08:00
以下来自Python Cookbook:
更简便的写法是: d = [[None] * 2 for x in range(3)] 但是遵照Python的哲学,更推荐更规范和更具有可读性的写法: d = [[None for x in xrange(2)] for x in xrange(3)] |
2
charnugagoo OP @hhrmatata
我现在需要初始化一个五维list ToT,这两种写法都很丑陋啊。。 |
3
sillyousu 2013-06-01 10:40:38 +08:00
def gen_list(dem, rang):
----if dem == 1: --------return [None for x in range(rang)] ----else: --------return [gen_list(dem-1, rang) for x in range(rang)] 这样? 五维,感觉不管怎么搞都是不好搞。 想到了 list[0][1][2][3][4] 和很多层的循环嵌套。 |
4
hhrmatata 2013-06-01 11:17:49 +08:00
构造递归函数,得到任何维度的初始化:
def make(dims, n, init_value): if n == 1: return [init_value for i in range(dims[n - 1])] else: return [make(dims, n - 1, init_value) for i in range(dims[n - 1])] >>> dims1 = [2, 3] >>> print make(dims1, 2, None) [[None, None], [None, None], [None, None]] >>> dims2 = [1, 2, 3, 4, 5] >>> print make(dims2, 5, 0) [[[[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]]], [[[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]]], [[[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]]], [[[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]]], [[[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]], [[0], [0]]]]] |
5
hhrmatata 2013-06-01 11:20:16 +08:00
好吧,代码不能缩进;回复后又不能修改
|