I have a tuple ([1,2,3], [4,5,6]) and I want to reverse the list inside so that it becomes ([3,2,1],[6,5,4]) without having to create a new tuple and adding elements to it. The closest I've gotten is:
我有一个元组([1,2,3],[4,5,6]),我想反转里面的列表,使它成为([3,2,1],[6,5,4])无需创建新元组并向其添加元素。我最接近的是:
my_func(....):
for i in tuple(...):
i = i[::-1]
return tuple(....)
problem is that while i prints out what I want..the tuple was never changed
问题是,当我打印出我想要的东西时......元组从未改变过
2 个解决方案
#1
8
Tuples are immutable but the objects contained by them can be either mutable or immutable, so if we modify a mutable object contained by the tuple then the change will be reflected at all the references of that object, that includes the tuple as well.
元组是不可变的,但它们包含的对象可以是可变的或不可变的,因此如果我们修改元组包含的可变对象,那么更改将反映在该对象的所有引用上,包括元组。
As in this case we've lists, so, all we need to do is to loop over the tuple and call .reverse()
on the lists.
在这种情况下,我们列出了,所以我们需要做的就是遍历元组并在列表上调用.reverse()。
>>> t = ([1,2,3], [4,5,6])
>>> for x in t:
... x.reverse()
...
>>> t
([3, 2, 1], [6, 5, 4])
Another example:
另一个例子:
>>> x = [1, 2, 3]
>>> t = (x, 'abc')
>>> x.reverse()
>>> t
([3, 2, 1], 'abc')
>>> x
[3, 2, 1]
#2
0
As frostnational says, tuples are immutable, so you will have to create new ones.
正如霜冻所说,元组是不可改变的,所以你必须创造新元组。
You could do something like this:
你可以这样做:
>>> a = ([1,2,3],[4,5,6])
>>> b = map(lambda t: reversed(t), a)
>>> for sublist in b:
... for item in sublist:
... print(item)
...
3
2
1
6
5
4
#1
8
Tuples are immutable but the objects contained by them can be either mutable or immutable, so if we modify a mutable object contained by the tuple then the change will be reflected at all the references of that object, that includes the tuple as well.
元组是不可变的,但它们包含的对象可以是可变的或不可变的,因此如果我们修改元组包含的可变对象,那么更改将反映在该对象的所有引用上,包括元组。
As in this case we've lists, so, all we need to do is to loop over the tuple and call .reverse()
on the lists.
在这种情况下,我们列出了,所以我们需要做的就是遍历元组并在列表上调用.reverse()。
>>> t = ([1,2,3], [4,5,6])
>>> for x in t:
... x.reverse()
...
>>> t
([3, 2, 1], [6, 5, 4])
Another example:
另一个例子:
>>> x = [1, 2, 3]
>>> t = (x, 'abc')
>>> x.reverse()
>>> t
([3, 2, 1], 'abc')
>>> x
[3, 2, 1]
#2
0
As frostnational says, tuples are immutable, so you will have to create new ones.
正如霜冻所说,元组是不可改变的,所以你必须创造新元组。
You could do something like this:
你可以这样做:
>>> a = ([1,2,3],[4,5,6])
>>> b = map(lambda t: reversed(t), a)
>>> for sublist in b:
... for item in sublist:
... print(item)
...
3
2
1
6
5
4