我在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, 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
关于python - 循环末尾的逗号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290408/