簡體   English   中英

按數字順序對列表進行排序

[英]Sort list in a numeric order

我計划按數字順序對以下列表進行排序

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

您必須傳遞key才能應用您的自定義排序願望。

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

lambda作用是將字符串一對一地取出提取點( '.' )前面的值並將其轉換為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']

要么:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM