【问题标题】:python 3 sorting a list of tuples by the highest numberpython 3按最高数字对元组列表进行排序
【发布时间】:2022-01-25 23:05:07
【问题描述】:

我该如何排序:

 [('Pineapple', 1), ('Apple', 2), ('Banana', 1)]

进入这个:

['Apple','Pineapple','Banana']

我的意思是按顺序对它进行排序,最高数字将位于新列表的左侧(如果它们具有相同的数字,那并不重要)。 我试过用这个:

sorted(fruitlist, key=lambda x: x[0])

但还是没有如我所愿

【问题讨论】:

  • sorted(fruitlist, key=lambda x: x[1]) ? x[0] 仍将按第一个元组元素排序,即字符串
  • 然后要先得到最大的数,使用sorted(fruitlist, key=lambda x: x[1], reverse=True)

标签: python list sorting


【解决方案1】:

如果要数字降序,可以按数字的负数排序:

sorted(fruitlist, key=lambda x: -x[1])  # x[1] is the number 
                                        # (x[0] is the string)

对于该数据类型和其他数据类型,您可以使用 sorted 函数的 reverse=True 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-28
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多