Add another tuple to a tuple of tuples

后端 未结 4 698
猫巷女王i
猫巷女王i 2021-02-01 12:34

I have the following tuple of tuples:

my_choices=(
         (\'1\',\'first choice\'),
         (\'2\',\'second choice\'),
         (\'3\',\'third choice\')
)


        
相关标签:
4条回答
  • 2021-02-01 12:41

    Don't convert to a list and back, it's needless overhead. + concatenates tuples.

    >>> foo = ((1,),(2,),(3,))
    >>> foo = ((0,),) + foo
    >>> foo
    ((0,), (1,), (2,), (3,))
    
    0 讨论(0)
  • 2021-02-01 12:46

    Build another tuple-of-tuples out of another_choice, then concatenate:

    final_choices = (another_choice,) + my_choices
    

    Alternately, consider making my_choices a list-of-tuples instead of a tuple-of-tuples by using square brackets instead of parenthesis:

    my_choices=[
         ('1','first choice'),
         ('2','second choice'),
         ('3','third choice')
    ]
    

    Then you could simply do:

    my_choices.insert(0, another_choice)
    
    0 讨论(0)
  • Alternatively, use the tuple concatenation

    i.e.

    
    final_choices = (another_choice,) + my_choices
    
    0 讨论(0)
  • 2021-02-01 12:55

    What you have is a tuple of tuples, not a list of tuples. Tuples are read only. Start with a list instead.

    >>> my_choices=[
    ...          ('1','first choice'),
    ...          ('2','second choice'),
    ...          ('3','third choice')
    ... ]
    >>> my_choices.insert(0,(0,"another choice"))
    >>> my_choices
    [(0, 'another choice'), ('1', 'first choice'), ('2', 'second choice'), ('3', 'third choice')]
    

    list.insert(ind,obj) inserts obj at the provided index within a list... allowing you to shove any arbitrary object in any position within the list.

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