【问题标题】:Move the highest value to start of list [closed]将最大值移动到列表的开头[关闭]
【发布时间】:2022-08-03 16:49:09
【问题描述】:

目标:将list 中的最大值移动到index: 0,而不重新排序任何其他元素。

最Pythonic的方法是什么?

例子:

[0.013, 0.726, 0.22323, 5.08, 1.23432]

期望的输出:

[5.08, 0.013, 0.726, 0.22323, 1.23432]
  • 你有没有发现任何怪诞的方法…?
  • 感谢@deceze 的评论

标签: python python-3.x list


【解决方案1】:

这是一个基于列表理解的方法:

inp = [0.013, 0.726, 0.22323, 5.08, 1.23432]
output = [max(inp)] + [x for x in inp if x != max(inp)]
print(output)  # [5.08, 0.013, 0.726, 0.22323, 1.23432]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2015-02-04
    • 2014-08-06
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2020-04-01
    相关资源
    最近更新 更多