Tuple value by key

后端 未结 5 1202
滥情空心
滥情空心 2020-12-08 19:21

Is it possible to get Value out of tuple:

TUPLE = (
    (\'P\', \'Shtg1\'),
    (\'R\', u\'Shtg2\'),
    (\'D\', \'Shtg3\'),
)

by calling S

相关标签:
5条回答
  • 2020-12-08 19:55

    Instead of moving to full dictionaries you can try using a named tuple instead. More information in this question.

    Basically you define tags for the fields and then are able to refer to them as value.tag1, etc.

    Quoting the docs:

    Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

    0 讨论(0)
  • 2020-12-08 20:03

    The canonical data structure for this type of queries is a dictionary:

    In [1]: t = (
       ...:     ('P', 'Shtg1'),
       ...:     ('R', u'Shtg2'),
       ...:     ('D', 'Shtg3'),
       ...: )
    
    In [2]: d = dict(t)
    
    In [3]: d['P']
    Out[3]: 'Shtg1'
    

    If you use a tuple, there is no way to avoid looping (either explicit or implicit).

    0 讨论(0)
  • 2020-12-08 20:04

    You want to use a dictionary instead.

    d = { 'P': 'Shtg1', 'R': u'Shtg2', 'D':'Shtg3' }
    

    And then you can access the key like so:

    d['P'] # Gets 'Shtg1'
    
    0 讨论(0)
  • 2020-12-08 20:08

    dict(TUPLE)[key] will do what you want.

    There is a little memory overhead, but it's fast.

    0 讨论(0)
  • 2020-12-08 20:08

    To elaborate on Eduardo's answer with some code from the python shell.

    >>> from collections import namedtuple
    >>> MyType = namedtuple('MyType', ['P', 'R', 'D'])
    >>> TUPLE = MyType(P='Shtg1', R=u'Shtg2', D='Shtg3')
    >>> TUPLE
    MyType(P='Shtg1', R=u'Shtg2', D='Shtg3')
    
    >>> TUPLE.P
    'Shtg1'
    
    >>> TUPLE.R
    u'Shtg2'
    
    >>> TUPLE.D
    'Shtg3'
    
    >>> TUPLE[0:]
    ('Shtg1', u'Shtg2', 'Shtg3')
    

    Remember that tuples are immutable, and dictionaries are mutable. If you want immutable types, namedtuple might be the way to go.

    0 讨论(0)
提交回复
热议问题