按数字顺序排序列表

时间:2017-11-27 12:21:51

标签: python

我计划按数字顺序对以下列表进行排序

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']

我尝试了sortedsort(),但获得了相同的结果。

我想要的结果是

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

2 个答案:

答案 0 :(得分:5)

您必须传递key才能应用自定义排序愿望。

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

这个lambda做的是它逐个接受字符串,提取点前面的值('.')并将其转换为{ {1}}。基于该整数值,int被排序并返回。

备注:

list内置了一些假设。如果在第一个点之前出现的任何内容无法转换为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']

答案 1 :(得分:1)

>>> l = ['1. Introduction', '4. End', '2. Chapter 1', '3. Chapter 2']
>>> sorted(l, key=lambda s: int(s[:s.index('.')]))
['1. Introduction', '2. Chapter 1', '3. Chapter 2', '4. End']