Python-以正确的方式使用2D数组/列表
Python提供了许多创建二维列表/数组的方法。但是,必须知道这些方法之间的差异,因为它们会在代码中造成很难跟踪的复杂性。
示例
rows, cols = (5, 5) arr = [[0]*cols]*rows #lets change the first element of the 1st row to 1 & print the array arr[0][0] = 1 for row in arr: print(row) arr = [[0 for i in range(cols)] for j in range(rows)] #again in this new array lets change the 1st element of the first row # to 1 and print the array arr[0][0] = 1 for row in arr: print(row)
输出结果
[1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0]
热门推荐
10 农民朋友发财祝福语简短
11 教练生日祝福语 简短独特
12 高考祝福语简短10字
13 宝宝生日祝福语大全简短
14 初升高祝福语家长简短
15 春天变冷祝福语简短
16 奶奶生日感恩祝福语简短
17 师姐毕业送花祝福语简短
18 简短的祝福语12字