我正在使用循环来创建元组,并且我想将这些元组插入到一个大的元组中。
假设我的输入是(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如果有人能帮我解决这个问题,我将不胜感激。提前感谢!
发布于 2019-10-13 11:17:23
您在这里不需要元组;您需要一个列表。元组是不可变的;一旦创建,就不能添加到其中。
然而,列表可以被append到:
big_list = []
. . .
big_list.append(tup)
print(big_list) # [(1, 2, 3), (1, 2, 3)]发布于 2019-10-13 11:15:48
正如@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中查看它
https://stackoverflow.com/questions/58360253
复制相似问题