循环结束时逗号是什么意思?

时间:2017-07-24 21:32:19

标签: python loops

我在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 个答案:

答案 0 :(得分:1)

尾随逗号使其成为元组的元组:

 iterate(obj.jsonIsOk);

>>> (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!

答案 1 :(得分:0)

逗号使(I,J)成为另一个元组的一部分。它相当于((I,J),)