python - 将另一个元组添加到元组的元组中

标签 python tuples

我有以下元组:

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

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

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

我该怎么做?

结果是:

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

最佳答案

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

final_choices = (another_choice,) + my_choices

或者,考虑通过使用方括号而不是括号使 my_choices 成为元组列表而不是元组:

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

那么你可以这样做:

my_choices.insert(0, another_choice)

关于python - 将另一个元组添加到元组的元组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3523048/

相关文章:

arrays - 闭包数组简写 : Xcode Swift: Expression too complex to be solved in a reasonable time

Python 将包含列表元组的字符串解压为变量

python - 需要有关以空格开头的正则表达式的帮助

python - 使用 Matplotlib 绘制日内 OHLC 图表的问题

Python 元组列表

python - 在 Django 的 installed_apps 中使用元组与列表有关系吗

python - 在循环内保留过滤器输出

python - Python OrderedSet.issuperset() 中的意外行为

Python Psycopg2 cursor.execute 返回 None

python - 将多个过滤器应用于元组列表