2017-07-24 59 views
1

我從leetcode的討論部分看到了代碼。我真的不明白循環結束時逗號的含義。循環結尾的逗號意味着什麼

def wallsAndGates(self, rooms): 
    q = [(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r] 
    for i, j in q: 
     for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1): 
      if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) and rooms[I][J] > 2**30: 
       rooms[I][J] = rooms[i][j] + 1 
       q += (I, J), 
+2

它使一個元組包含一個元組...你有沒有嘗試在repl上檢查自己?無論如何,這似乎是一個糟糕的做法'q.append((I,J))' –

+0

如果我沒有錯,無效,因爲你不能連接一個元組和列表。 –

+0

@COLDSPEED否它不是無效的,因爲它有效。實際上它似乎與'+ ='右側的任何迭代器一起工作。 – Gribouillis

回答

0

逗號使(I,J)成爲另一個元組的一部分。這是((I,J),)

1

後面的逗號使得它元組的元組等價的:

>>> (1, 2) # how you normally see tuples 
(1, 2) 
>>> 1, 2 # but the parenthesis aren't really needed 
(1, 2) 
>>> 1,  # bare comma makes this a tuple 
(1,) 
>>>   # parenthesis separate the inner tuple from the trailing comma 
>>> (1, 2), # giving a tuple of tuples 
((1, 2),) 

q += (I, J),是相當尷尬,並創建額外的不必要的元組。

的代碼會被更好地表述爲

q.append((I, J)) 

有趣的是它不能寫成

q += (I, J) # no trailing comma works differently! 

,因爲它本來相當於

q.extend((I, J)) # extend, not append! "I" and "J" no longer grouped in a tuple