【问题标题】:Sorting a tuple by its float element按浮点元素对元组进行排序
【发布时间】:2013-12-03 05:59:10
【问题描述】:

我正在尝试按数字的值对这个元组进行排序,以便按降序重新排列:

l =[('orange', '3.2'), ('apple', '30.2'), ('pear', '4.5')]

如:

l2 =[('apple', '30.2'), ('pear', '4.5'), ('orange', '3.2')]

我正在尝试使用以下方法对其进行排序:

l2 = ((k,sorted(l2), key=lambda x: float(x[1]), reverse=True)))
       [value for pair in l2 for value in pair]

但我收到错误消息:

TypeError: float() argument must be a string or a number, not 'tuple'

如何更正此问题,以便表明我想按每对中的数字进行排序? Python 语法仍然让我很困惑,因为我对它很陌生。任何帮助将不胜感激。

【问题讨论】:

    标签: python sorting python-3.x tuples


    【解决方案1】:

    你把语法弄混了;你快到了。这有效:

    l2 = sorted(l, key=lambda x: float(x[1]), reverse=True)
    

    例如调用sorted() 函数,并传入要排序的列表作为第一个参数。其他两个参数是关键字参数(key 和 reverse)。

    演示:

    >>> l = [('orange', '3.2'), ('apple', '30.2'), ('pear', '4.5')]
    >>> sorted(l, key=lambda x: float(x[1]), reverse=True)
    [('apple', '30.2'), ('pear', '4.5'), ('orange', '3.2')]
    

    您还可以就地对列表进行排序:

    l.sort(key=lambda x: float(x[1]), reverse=True)
    

    使用相同的两个关键字参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 2016-02-01
      • 2015-06-21
      • 1970-01-01
      • 2019-09-01
      • 2014-10-19
      相关资源
      最近更新 更多