Extracting the a value from a tuple when the other values are unused

前端 未结 6 1287
一整个雨季
一整个雨季 2021-02-04 10:42

I have a tuple foo which contains something I don\'t care about and something I do.

foo = (something_i_dont_need, something_i_need)
<
6条回答
  •  滥情空心
    2021-02-04 10:49

    Another possibility is to create a named tuple and use that in your return value. Then you can access the value you want by "name."

    MyTuple = collections.namedtuple('MyTuple', 'ignored needed')
    

    Then you can make

    foo = (something_i_dont_need, something_i_need)
    

    into

    foo = MyTuple(something_i_dont_need, something_i_need)
    

    and then say

    x = foo.needed
    

    instead of

    x = foo[1]
    

    Performance-wise, this may not be the best. But I think it can sometimes make writing and understanding the code easier. And it is an alternative to some of the other solutions.

提交回复
热议问题