analogique Python de la fonction de natsort de PHP (trier une liste en utilisant un algorithme à « ordre naturel ») [en double]

StackOverflow https://stackoverflow.com/questions/2545532

  •  23-09-2019
  •  | 
  •  

Question

    

Cette question a déjà une réponse ici:

         

Je voudrais savoir s'il y a quelque chose de similaire à PHP natsort fonction en Python?

l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
l.sort()

donne:

['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']

mais je voudrais obtenir:

['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

UPDATE

base de la solution sur ce lien

def try_int(s):
    "Convert to integer if possible."
    try: return int(s)
    except: return s

def natsort_key(s):
    "Used internally to get a tuple by which s is sorted."
    import re
    return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):
    "Natural string comparison, case sensitive."
    return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
    "Natural string comparison, ignores case."
    return natcmp(a.lower(), b.lower())

l.sort(natcasecmp);
Était-ce utile?

La solution

De ma réponse algorithme de tri naturel :

import re
def natural_key(string_):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]

Exemple:

>>> L = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> sorted(L)
['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
>>> sorted(L, key=natural_key)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

Pour soutenir les chaînes Unicode, .isdecimal() doit être utilisé au lieu de .isdigit(). Voir l'exemple dans @ commentaire de phihag . Connexes: Comment révéler propriété valeur numérique Unicodes

.

.isdigit() peut aussi échouer (valeur de retour qui n'est pas acceptée par int()) pour un bytestring sur Python 2 dans certains endroits, par exemple, '\ XB2' ( '²') dans locale CP1252 sous Windows .

Autres conseils

Vous pouvez consulter le tiers natsort bibliothèque PyPI:

>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

La divulgation complète, je suis l'auteur.

Cette fonction peut être utilisée comme argument pour key= sorted en Python 2 .x et 3.x:

def sortkey_natural(s):
    return tuple(int(part) if re.match(r'[0-9]+$', part) else part
                for part in re.split(r'([0-9]+)', s))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top