38

有没有办法编写以下函数,以便我的 IDE 不会抱怨该是未使用的变量?

def get_selected_index(self):
    (path, column) = self._tree_view.get_cursor()
    return path[0]

在这种情况下,我不关心元组中的第二项,只想在解包时丢弃对它的引用。

4

4 回答 4

55

在 Python 中,_通常用作被忽略的占位符。

(path, _) = self._treeView.get_cursor()

您还可以避免拆包,因为元组是可索引的。

def get_selected_index(self):
    return self._treeView.get_cursor()[0][0]
于 2010-09-27T09:16:24.187 回答
4

如果您不关心第二项,为什么不直接提取第一项:

def get_selected_index(self):
    path = self._treeView.get_cursor()[0]
    return path[0]
于 2010-09-27T11:28:27.113 回答
1

对的,这是可能的。具有约定的公认答案_仍然解包,只是到一个占位符变量。

您可以通过以下方式避免这种情况itertools.islice

from itertools import islice

values = (i for i in range(2))

res = next(islice(values, 1, None))  # 1

这将给出与res以下相同的结果:

_, res = values

如上所述,该解决方案适用于values不是可索引集合的可迭代对象,例如listor tuple

于 2018-09-10T11:25:29.390 回答
0

挺好看的,不知道演技好不好。

a = (1, 2, 3, 4, 5)
x, y = a[0:2]
于 2016-04-20T10:45:35.463 回答