gpt4 book ai didi

python - 将元组插入元组

转载 作者:太空宇宙 更新时间:2023-11-04 04:00:56 25 4
gpt4 key购买 nike

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

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

关于python - 将元组插入元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58360253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com