pyt*_*hon 4 python sorting list python-2.7
假设我有一个列表,我想按以下模式对数字进行排序:
A = [3, 30, 34, 256, 5, 9]
Run Code Online (Sandbox Code Playgroud)
排序单元处的数字第一,如果单位的地方数字是相同的,然后我们将比较tens place
,然后hundred place
。如果按此规则对A进行排序,则:
A = [9, 5, 34, 3, 30, 256]
9 is the highest digit at Unit place
5 is second highest
3, 34, 30 since unit digit is same here, we will compare tens place so 34 will come first here, then 3 and 30.
256 will come last since its unit place digit is 2 which is the lowest.
Suppose B = [100, 10, 1]
then after sorting B = [1, 10, 100]
Run Code Online (Sandbox Code Playgroud)
谁能分享一些Python方式解决此问题?
我已经尝试过了,sorted(nums, key=lambda x: int(x[0]), reverse=True)
但是在这里我将如何tenth place digit
考虑呢?
更新:A = [1, 100, 10]
在这种情况下,排序后应该缺少一点A = [1, 10, 100]
。在示例中,我A = [3, 30, 34, 256, 5, 9]
经过排序后给出了这里A = [9, 5, 34, 3, 30, 256]
。
总体逻辑是,我想加入所有数字并创建一个最大的数字。
我认为您只需要str作为关键:
In [11]: sorted(A, key=str, reverse=True)
Out[11]: [9, 5, 34, 30, 3, 256]
Run Code Online (Sandbox Code Playgroud)
最初,我读到您的问题,您需要反转的数字:
In [12]: sorted(A, key=lambda x: str(x)[::-1])
Out[12]: [30, 3, 34, 5, 256, 9]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1318 次 |
最近记录: |