[英]Iterating through a 2D array
我正在編寫一些 python 代碼來遍歷二維數組 A,如果數組中存在負數,則打印“negval”,否則打印“positive”。 此代碼生成編譯器錯誤“'int' 對象不可迭代”。 有人可以解釋這個錯誤以及如何解決它嗎?
A = [[0,1,1], [1,0,1], [1,1,0]]
r,c = 0
for r in range(3):
for c in range(3):
if A[r][c] < 0:
print 'negval'
print 'positive'
1。
問題來自此行,您應該具有以下追溯:
>>> r, c = 0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-506be499ea74> in <module>()
----> 1 r, c = 0
TypeError: 'int' object is not iterable
您嘗試進行列表解壓縮,但0
不是列表。 如果希望r
和c
為0
,則可以執行以下操作:
r, c = 0, 0
# or
r = c = 0
2。
為了遍歷您的列表,我將做:
for a, b, c in A:
...
其中a
, b
, c
將是每個列表的三個元素。
r,c = 0
這行不起作用,因為您正試圖解壓縮一個不可迭代的值。 寧可
r=c=0
但是,使用range
以及硬編碼編號並不是一個好主意。 而是使用any
:
print "negval" if any(element<0 for innerList in A for element in innerList) else "positive"
如果您不滿意any
,請執行以下操作:
negative=False
for innerList in A:
for element in innerList:
if element<0:
negative=True
print 'negval' if negative else "positive"
Remove the definition of r,c = 0 which is not needed causing the issue.
要么
r, c = 0,0
要么
r = c = 0
請定義一個函數/方法以使其看起來更好
同樣,您可以使用xrange函數,該函數將產生一個整數生成器。
def test_2d_parse_array():
"""
"""
A = [[0,1,1], [1,0,1], [1,1,0]]
r = c = 0
for r in xrange(3):
for c in xrange(3):
if A[r][c] < 0:
return 'negval'
return 'positive'
if __name__ == '__main__':
test_2d_parse_array()
您r, c = 0
。 這是行不通的,因為0不是可迭代的類型。 您必須將r和c分別分配給0:
r = 0
c = 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.