Python 将另一个元组添加到元组的元组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3523048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:33:04  来源:igfitidea点击:

Add another tuple to a tuple of tuples

pythontuples

提问by John

I have the following tuple of tuples:

我有以下元组元组:

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

and I want to add another tuple to the start of it

我想在它的开头添加另一个元组

another_choice = ('0', 'zero choice')

How can I do this?

我怎样才能做到这一点?

the result would be:

结果将是:

final_choices=(
             ('0', 'zero choice')
             ('1','first choice'),
             ('2','second choice'),
             ('3','third choice')
    )

采纳答案by Daniel Stutzbach

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

用 构建另一个元组元组another_choice,然后连接:

final_choices = (another_choice,) + my_choices

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

或者,考虑my_choices使用方括号而不是括号来制作元组列表而不是元组元组:

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

Then you could simply do:

然后你可以简单地做:

my_choices.insert(0, another_choice)

回答by whaley

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.

list.insert(ind,obj) 在列表中提供的索引处插入 obj ......允许您将任意对象推入列表中的任何位置。

回答by Katriel

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

回答by Brendan

Alternatively, use the tuple concatenation

或者,使用元组连接

i.e.

IE


final_choices = (another_choice,) + my_choices