python - 循环末尾的逗号是什么意思?

标签 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),

最佳答案

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

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

相关文章:

python - 增加/减少 WAV 文件 Python 的播放速度

python - Pandas 文档操作 k 至 1000

python - 简单数字识别中的OpenCV Python错误

mysql - 遍历触发器中的临时表

python - 是否可以有一个没有循环的进度条?

jquery - 影响相同ID的多个元素?

python - 如何在 Python 中压缩嵌套循环

jsp - 使用 c :foreach (JSP/JSTL), 变量迭代 ArrayList 不起作用

python - 使用 python 和 beautifulsoup 选择一组表格下的一组特定单元格

Python - 从较大的矩阵中提取较小的矩阵