Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

natural.py 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """isort/natural.py.
  2. Enables sorting strings that contain numbers naturally
  3. usage:
  4. natural.nsorted(list)
  5. Copyright (C) 2013 Timothy Edmund Crosley
  6. Implementation originally from @HappyLeapSecond stack overflow user in response to:
  7. https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
  8. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  9. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  10. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  11. to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in all copies or
  13. substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  15. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  16. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  17. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  18. OTHER DEALINGS IN THE SOFTWARE.
  19. """
  20. import re
  21. def _atoi(text):
  22. return int(text) if text.isdigit() else text
  23. def _natural_keys(text):
  24. return [_atoi(c) for c in re.split(r'(\d+)', text)]
  25. def nsorted(to_sort, key=None):
  26. """Returns a naturally sorted list"""
  27. if key is None:
  28. key_callback = _natural_keys
  29. else:
  30. def key_callback(item):
  31. return _natural_keys(key(item))
  32. return sorted(to_sort, key=key_callback)