How to Implement Python's Equivalent of PHP's natsort Function?

Mary-Kate Olsen
Release: 2024-11-05 21:36:02
Original
437 people have browsed it

How to Implement Python's Equivalent of PHP's natsort Function?

Python's Analog to PHP's natsort Function: Natural Order Sorting

Natural sorting algorithms sort lists of strings in a human-readable order, grouping numbers and other characters together. Unlike the default sort method, which treats "12" as less than "3", natural sorts would produce ["1", "10", "12", "3"].

In Python, one can implement a natural sorting function using a custom key function. The following code snippet provides an implementation similar to PHP's natsort:

<code class="python">import re

def natural_key(string_):
    """See https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]</code>
Copy after login

Example:

<code class="python">L = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
sorted(L)
# Output: ['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
sorted(L, key=natural_key)
# Output: ['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']</code>
Copy after login

For Unicode strings, use isdecimal() instead of isdigit(). For bytestrings on Python 2, bytestring.decode().isdigit() should be used.

The above is the detailed content of How to Implement Python's Equivalent of PHP's natsort Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!