我有以下元组元组:
my_choices=(
('1','first choice'),
('2','second choice'),
('3','third choice')
)
Run Code Online (Sandbox Code Playgroud)
我想在它的开头添加另一个元组
another_choice = ('0', 'zero choice')
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
结果将是:
final_choices=(
('0', 'zero choice')
('1','first choice'),
('2','second choice'),
('3','third choice')
)
Run Code Online (Sandbox Code Playgroud)
Dan*_*ach 55
构建另一个tuple-of-tuples another_choice,然后连接:
final_choices = (another_choice,) + my_choices
Run Code Online (Sandbox Code Playgroud)
或者,考虑my_choices使用方括号而不是括号来制作元组列表而不是元组元组:
my_choices=[
('1','first choice'),
('2','second choice'),
('3','third choice')
]
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地做:
my_choices.insert(0, another_choice)
Run Code Online (Sandbox Code Playgroud)
Kat*_*iel 17
不要转换为列表并返回,这是不必要的开销.+连接元组.
>>> foo = ((1,),(2,),(3,))
>>> foo = ((0,),) + foo
>>> foo
((0,), (1,), (2,), (3,))
Run Code Online (Sandbox Code Playgroud)
或者,使用元组连接
IE
final_choices = (another_choice,) + my_choices
Run Code Online (Sandbox Code Playgroud)