use*_*420 1 python tuples list python-2.x
我有一个元组列表:
ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]
我想颠倒列表中每个元组的顺序。
ls = [('there', 'hello'), ('up', 'whats'), ('idea', 'no')]
我知道元组是不可变的,所以我需要创建新的元组。我不确定最好的方法是什么。我可以将元组列表更改为列表列表,但我认为可能有更有效的方法来解决这个问题。
只需按照以下几行使用列表理解:
ls = [tpl[::-1] for tpl in ls]
Run Code Online (Sandbox Code Playgroud)
这使用典型的[::-1] 切片模式来反转元组。
另请注意,列表本身不是不可变的,因此如果您需要改变原始列表,而不仅仅是重新绑定ls变量,您可以使用切片赋值:
ls[:] = [tpl[::-1] for tpl in ls]
Run Code Online (Sandbox Code Playgroud)
这是基于循环的方法的简写形式à la:
for i, tpl in enumerate(ls):
ls[i] = tpl[::-1]
Run Code Online (Sandbox Code Playgroud)