如何将元素存储在元组中?python - 如何将元素存储在元组中
我这样做:
for i in range (0, capacity):
for elements in self.table[i]:
# STORE THE ALL THE ELEMENTS IN THE TUPLE
如何将元素存储在元组中?python - 如何将元素存储在元组中
我这样做:
for i in range (0, capacity):
for elements in self.table[i]:
# STORE THE ALL THE ELEMENTS IN THE TUPLE
这是那么容易,因为t = tuple(self.table[i])
我想这是你想要的。
x = []
for i in range (0, capacity):
for elements in self.table[i]:
x.append(elements)
t = tuple(x)
元组是不可变的。你可以创建一个元组。但是你不能将元素存储到已经创建的元组中。将元素列表创建(或转换)为元组。只需tuple()
吧。
t = tuple([1,2,3])
在你的情况下,它是
t = tuple(self.table[:capacity])
因为你还没有告诉我们 - 我们只能猜测是什么表看起来像 如果是例如一个列表的列表,你可以这样做得到元组的元组
>>> table =[[1,2,3],[4,5,6],[7,8,9]]
>>> tuple(map(tuple, table))
((1, 2, 3), (4, 5, 6), (7, 8, 9))
>>> capacity=2
>>> tuple(map(tuple, table[:capacity]))
((1, 2, 3), (4, 5, 6))