开发者

Is it possible to unpack a tuple in Python without creating unwanted variables?

开发者 https://www.devze.com 2023-01-17 22:43 出处:网络
Is there a way to write the following function so that my IDE doesn\'t complain that column is an unused variable?

Is there a way to write the following function so that my IDE doesn't complain that column is an unused variable?

def get_selected_index(self):
    (path, column) = self._tree开发者_如何学Go_view.get_cursor()
    return path[0]

In this case I don't care about the second item in the tuple and just want to discard the reference to it when it is unpacked.


In Python the _ is often used as an ignored placeholder.

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

You could also avoid unpacking as a tuple is indexable.

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


If you don't care about the second item, why not just extract the first one:

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


Yes, it is possible. The accepted answer with _ convention still unpacks, just to a placeholder variable.

You can avoid this via itertools.islice:

from itertools import islice

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

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

This will give the same res as below:

_, res = values

The solution, as demonstrated above, works when values is an iterable that is not an indexable collection such as list or tuple.


it looks pretty, I don't know if a good performance.

a = (1, 2, 3, 4, 5)
x, y = a[0:2]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号