通过float元素对元组进行排序

时间:2013-11-19 15:35:30

标签: python sorting python-3.x tuples

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

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 个答案:

答案 0 :(得分:10)

你搞砸了语法;你快到了。这有效:

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

e.g。调用sorted()函数,并传入列表作为第一个参数排序。另外两个参数是关键字参数(keyreverse)。

演示:

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

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