【问题标题】:Reversing the order of a list of lists or list of tuples反转列表列表或元组列表的顺序
【发布时间】: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


【解决方案1】:

只需使用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]

【讨论】:

    【解决方案2】:

    输入:

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

    ls = [(f,s) for s,f in ls]
    print(ls)
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2022-11-04
      • 2022-09-27
      相关资源
      最近更新 更多