我开始使用python,我尝试使用一个二维列表,我开始在每个地方都用相同的变量填充。我想到了这个:
def initialize_twodlist(foo):
twod_list = []
new = []
for i in range (0, 10):
for j in range (0, 10):
new.append(foo)
twod_list.append(new)
new = []
它给出了预期的结果,但感觉像是一种变通方法。有更简单/更短/更优雅的方法吗?
你可以这样做:
[[element] * numcols] * numrows
例如:
>>> [['a'] *3] * 2
[['a', 'a', 'a'], ['a', 'a', 'a']]
但这有一个不受欢迎的副作用:
>>> b = [['a']*3]*3
>>> b
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
>>> b[1][1]
'a'
>>> b[1][1] = 'b'
>>> b
[['a', 'b', 'a'], ['a', 'b', 'a'], ['a', 'b', 'a']]
另一种方法是使用字典来保存二维数组。
twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0
它可以保存任何1D, 2D值,并将其初始化为0或任何其他int值,使用集合。
import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1