[英]Add another tuple to a tuple of tuples
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')
)
Build another tuple-of-tuples out of another_choice
, then concatenate: 从another_choice
构建另一个元组元组,然后连接:
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
成为元组列表而不是元组元组:
my_choices=[
('1','first choice'),
('2','second choice'),
('3','third choice')
]
Then you could simply do: 然后你可以简单地做:
my_choices.insert(0, another_choice)
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,))
Alternatively, use the tuple concatenation 或者,使用元组连接
ie 即
final_choices = (another_choice,) + my_choices
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 ...允许您在列表中的任何位置推送任意对象。
You could use the "unpacking operator" (*) to create a new tuple您可以使用“解包运算符”(*)创建一个新元组
tpl = ((2, 11), (3, 10),)
tpl = (*tpl, (5, 8))
print(tpl) #prints ((2, 11), (3, 10), (5, 8))
my_choices=(
('1','first choice'),
('2','second choice'),
('3','third choice')
)
new=('0','zero choice')
list=[item for item in my_choices]
list.insert(0,new)
my_choices=tuple(list)
print(my_choices)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.