按照元组中浮点数元素排序

3
我将尝试根据数字的值对该元组进行排序,以便按降序重新排列:
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语法仍然让我感到困惑。非常感谢您的帮助。

1个回答

12

你把语法搞混了;你差不多就成功了。这样做可以:

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

例如,调用sorted()函数,并将要排序的列表作为第一个参数传入。另外两个参数是关键字参数(keyreverse)。

Demo:

>>> 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)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接