首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将元组插入元组

将元组插入元组
EN

Stack Overflow用户
提问于 2019-10-13 11:02:37
回答 2查看 145关注 0票数 2

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

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

我尝试了多种方法,但还是想不出该怎么做。

代码语言:javascript
复制
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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-13 11:17:23

您在这里不需要元组;您需要一个列表。元组是不可变的;一旦创建,就不能添加到其中。

然而,列表可以被append到:

代码语言:javascript
复制
big_list = []
. . .
big_list.append(tup)

print(big_list)  # [(1, 2, 3), (1, 2, 3)]
票数 1
EN

Stack Overflow用户

发布于 2019-10-13 11:15:48

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

正如here所见。如果你想创建一个元组的元组,你只需要使用下面的代码。

代码语言:javascript
复制
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中查看它

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58360253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档