我试图组合多个元组,但不知道如何。我知道如何创建一个元组,但我不太确定如何将它们组合在一起。我想继续追加(实际上不是附加因为我不想要一个列表)。我从每一行中拉出一根弦并将所有元组放在一起
x = (132, 534, 4)
y = (345, 531, 1)
z = (212, 421, 5)
我想要的回复
(132, 534, 4), (345, 531, 1), (212, 421, 5)
答案 0 :(得分:6)
您的示例中的元组可以像这样创建:
>>> # The following line is equivalent to: new_tuple = (x, y, z)
>>> new_tuple = x, y, z
>>> new_tuple
((132, 534, 4), (345, 531, 1), (212, 421, 5))
>>>
但是,因为元组是不可变的(创建后无法更改)序列,所以每次要“追加”它时都需要创建一个新元素:
>>> new_tuple = x, y, z
>>> new_tuple
((132, 534, 4), (345, 531, 1), (212, 421, 5))
>>> w = 1, 2, 3 # This is another tuple that needs to go inside new_tuple
>>> new_tuple = x, y, z, w # So, we have to rebuild new_tuple to include it
>>> new_tuple
((132, 534, 4), (345, 531, 1), (212, 421, 5), (1, 2, 3))
>>>
这就是为什么最好只使用一个列表,它是一个可变的(可以在创建后更改)序列,它具有append
方法:
>>> new_list = [x, y, z] # Square brackets make a list
>>> new_list
[(132, 534, 4), (345, 531, 1), (212, 421, 5)]
>>> w = 1, 2, 3
>>> new_list.append(w) # Add w to new_list without rebuilding it
>>> new_list
[(132, 534, 4), (345, 531, 1), (212, 421, 5), (1, 2, 3)]
>>>
答案 1 :(得分:3)
最简单的方法可能是这个
x = (132, 534, 4)
y = (345, 531, 1)
z = (212, 421, 5)
r = x, y, z