是否可以在Python中解压缩元组而不创建不需要的变量?

问题描述 投票:32回答:4

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

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

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

python tuples iterable-unpacking
4个回答
53
投票

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

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

您还可以避免解压缩,因为元组是可索引的。

def get_selected_index(self):
    return self._treeView.get_cursor()[0][0]

4
投票

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

def get_selected_index(self):
    path = self._treeView.get_cursor()[0]
    return path[0]

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是一个可迭代的,不是可转换的集合,如listtuple


0
投票

它看起来很漂亮,我不知道是否表现不错。

a = (1, 2, 3, 4, 5)
x, y = a[0:2]
© www.soinside.com 2019 - 2024. All rights reserved.