将元组插入元组

2024-04-26 05:45:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个循环来创建元组,我想把这些元组插入一个大元组。你知道吗

假设我的输入是(1,2,3),这是从每个循环生成的,我的预期输出是((1,2,3),(1,2,3))。你知道吗

我试过多种方法,但还是不知道怎么做。你知道吗

big_tup = ()

for i in range(2):
    tup = (1, 2, 3)

    # this will cause AttributeError: 'tuple' object has no attribute 'insert'
    big_tup.insert(tup) 

    # this will combine all tuples together, output: (1, 2, 3, 1, 2, 3)
    big_tup += tup

    # this will make duplicates of (), output: (((), 1, 2, 3), 1, 2, 3)
    big_tup = (big_tup,) + tup

如果有人能帮我解决这个问题,我将不胜感激。提前谢谢!你知道吗


Tags: 方法inforoutputobjectrangethiswill
2条回答

你不需要一个元组,你需要一个列表。元组是不可变的;一旦创建了元组,就不能添加元组。你知道吗

但是,列表可以append编辑为:

big_list = []
. . .
big_list.append(tup)

print(big_list)  # [(1, 2, 3), (1, 2, 3)]

正如@carcigenicate指出的here建议使用元组列表而不是元组的元组。你知道吗

here所示。如果您特别需要创建一个元组的元组,那么只需要使用下面的代码。你知道吗

big_tup = ()

for i in range(2):
    tup = (1, 2, 3)
    big_tup += (tup,) # this doesn't insert tup to big_tup, it is actually creating a new tuple and with the existing tuples and new tup using the same name

print(big_tup)
# ((1, 2, 3), (1, 2, 3))

在行动中看到它here

相关问题 更多 >