我有這個創建數組:如何在Python中循環我的2d數組?
numbers = []
for num in range(0,5):
nums = []
for inum in range(0,5):
nums.append(inum)
numbers.append(nums)
如何循環?我用for item in len(numbers):
它不起作用。 感謝
我有這個創建數組:如何在Python中循環我的2d數組?
numbers = []
for num in range(0,5):
nums = []
for inum in range(0,5):
nums.append(inum)
numbers.append(nums)
如何循環?我用for item in len(numbers):
它不起作用。 感謝
列表項是可迭代的,沒必要弄長,因爲他們將自己分配到與for..in結合第一可變..循環;
for item in numbers:
print "In first list: ", item
for num in item:
print " Getting number: ", num
輸出
In first list: [0, 1, 2, 3, 4]
Getting number: 0
Getting number: 1
Getting number: 2
Getting number: 3
Getting number: 4
In first list: [0, 1, 2, 3, 4]
Getting number: 0
Getting number: 1
...
for i in range(5):
for j in range(5):
print numbers[i][j]
雙環:
for row in numbers:
for cell in row:
print cell,
print
嘗試此。
[[col for col in range(5)] for row in range(5)]