Sort a list to form the largest possible number

前端 未结 8 1038
无人及你
无人及你 2020-11-27 20:29

I am trying to write a function that given a list of non negative integers, arranges them such that they form the largest possible number.

For example, given

8条回答
  •  暖寄归人
    2020-11-27 21:01

    One-liner using insights from Antti Haapala, PM 2Ring and Stefan Pochmann:

    from fractions import Fraction
    sorted(a, key=lambda n: Fraction(n, 10**len(str(n))-1), reverse=True)
    

    Given a = [50, 5, 51, 59, 2, 1, 9, 98]:

    [9, 98, 59, 5, 51, 50, 2, 1]
    

提交回复
热议问题