Skip to main content
 首页 » 编程设计

python之将元组插入元组

2024年11月01日8dyllove98

我正在使用循环创建元组,我想将这些元组插入到一个大元组中。

假设我的输入是 (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 

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

请您参考如下方法:

这里不需要元组;你想要一个 list 。元组是不可变的;它们一旦创建就无法添加。

然而,列表可以附加到:

big_list = [] 
. . . 
big_list.append(tup) 
 
print(big_list)  # [(1, 2, 3), (1, 2, 3)]