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

后端 未结 4 901
甜味超标
甜味超标 2020-12-29 02:21

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):
           


        
相关标签:
4条回答
  • 2020-12-29 02:46

    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]
    
    0 讨论(0)
  • 2020-12-29 02:56

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

    a = (1, 2, 3, 4, 5)
    x, y = a[0:2]
    
    0 讨论(0)
  • 2020-12-29 03:00

    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.

    0 讨论(0)
  • 2020-12-29 03:07

    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]
    
    0 讨论(0)
提交回复
热议问题