このコードは、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),
回答:
回答№1は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
回答№2の場合は0
コンマは(I、J)を別のタプルの一部にします。それは((I、J)、)と同等です