【发布时间】:2020-09-07 22:38:27
【问题描述】:
我有一个元组列表:
ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]
我想颠倒列表中每个元组的顺序。
ls = [('there', 'hello'), ('up', 'whats'), ('idea', 'no')]
我知道元组是不可变的,所以我需要创建新的元组。我不确定最好的方法是什么。我可以将元组列表更改为列表列表,但我认为可能有更有效的方法来解决这个问题。
【问题讨论】:
-
在 python2 中,
map(reversed, ls)就足够了,在 python3 中,您必须编写list(map(tuple, map(reversed, ls)))以获得相同的结果。列表理解是一种更好的方法
标签: python list tuples python-2.x