反转列表列表或元组列表的顺序

问题描述 投票:1回答:2

我有一个元组列表:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

我想反转列表中每个元组的顺序。

ls = [('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

我知道元组是不可变的,因此我需要创建新的元组。我不确定这是什么最好的方法。我可以将元组列表更改为列表列表,但是我认为可能会有更有效的方法进行此操作。

python list tuples python-2.x
2个回答
5
投票

只需在以下几行中使用list comprehension

ls = [tpl[::-1] for tpl in ls]

这使用典型的[::-1] slice模式来反转元组。

还请注意,列表本身并非一成不变,因此,如果您需要更改原始列表,而不仅仅是重新绑定ls变量,则可以使用slice assignment

ls[:] = [tpl[::-1] for tpl in ls]

这是基于循环的方法的简写形式:

for i, tpl in enumerate(ls):
    ls[i] = tpl[::-1]

0
投票

这里:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]
ls = [(f,s) for s,f in ls]
print(ls)
© www.soinside.com 2019 - 2024. All rights reserved.