Skip to main content
 首页 » 编程设计

python之按数字顺序对列表进行排序

2025年05月04日13虾米哥

我打算按数字顺序对以下列表进行排序

In [117]: print(alist) 
['1. Introduction', '10. Functional Programming Modules', '11. File and Directory Access', 
'12. Data Persistence', '13. Data Compression and Archiving', '14. File Formats', '15. Cryptographic Services', '16. Generic Operating System Services', '17. Concurrent Execution',  
'18. Interprocess Communication and Networking', '19. Internet Data Handling', '2. Built-in Function', '20. Structured Markup Processing Tools', '21. Internet Protocols and Support', '22. Multimedia Services', '23. Internationalization', '24. Program Frameworks', '25. Graphical User Interfaces with Tk', '26. Development Tools', '27. Debugging and Profiling', '28. Software Packaging and Distribution', '29. Python Runtime Services', '3. Built-in Constants', '30. Custom Python Interpreters', '31. Importing Modules', '32. Python Language Services', '33. Miscellaneous Services', '34. MS Windows Specific Services', '35. Unix Specific Services', '36. Superseded Modules', '37. Undocumented Modules', '4. Built-in Types', '5. Built-in Exceptions', '6. Text Processing Services', '7. Binary Data Services', '8. Data Types', '9. Numeric and Mathematical Modules'] 

我尝试了sorted、sort(),但得到了相同的结果。

我想要的结果是

['1.**', '2.**',... '10.**',... '19.**', '20.**'...] 

请您参考如下方法:

您必须传递一个键才能应用您的自定义排序愿望。

res = sorted(alist, key=lambda x: int(x.partition('.')[0])) 

这个 lambda 的作用是一个接一个地获取字符串,提取点前面的值 ('.') 并将其转换为 int。根据该整数值,列表 被排序并返回。


注意事项:

lambda 中内置了一些假设。如果第一个点之前的内容无法转换为 int,则会抛出错误。为避免这种情况,您可以使用以下更详细的版本:

def sort_helper(my_str, str_last=True): 
  try: 
    return int(my_str.partition('.')[0])  # kudos @JonClements 
  except ValueError: 
    return float('{}inf'.format({True: '+', False: '-'}[str_last])) # sends malformed inputs to the front or the back depending on the str_last flag 
 
alist = ['1. Introduction', '5. Built-in Exceptions', 'X. Not Implemented Yet'] 
res = sorted(alist, key=sort_helper) 
print(res)  # ['1. Introduction', '5. Built-in Exceptions', 'X. Not Implemented Yet'] 

或:

res = sorted(alist, key=lambda x: sort_helper(x, False)) 
print(res)  # ['X. Not Implemented Yet', '1. Introduction', '5. Built-in Exceptions']