Ordinamento senza distinzione tra maiuscole e minuscole, ordinamento della stringa in atto , in Python 2 OR 3 (testato in Python 2.7.17 e Python 3.6.9):
>>> x = ["aa", "A", "bb", "B", "cc", "C"]
>>> x.sort()
>>> x
['A', 'B', 'C', 'aa', 'bb', 'cc']
>>> x.sort(key=str.lower) # <===== there it is!
>>> x
['A', 'aa', 'B', 'bb', 'C', 'cc']
La chiave è key=str.lower
. Ecco come appaiono questi comandi con solo i comandi, per un facile copia-incolla in modo da poterli testare:
x = ["aa", "A", "bb", "B", "cc", "C"]
x.sort()
x
x.sort(key=str.lower)
x
Nota che se le tue stringhe sono stringhe unicode, comunque (come u'some string'
), solo in Python 2 (NON in Python 3 in questo caso) il x.sort(key=str.lower)
comando sopra fallirà e produrrà il seguente errore:
TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
Se ricevi questo errore, esegui l'upgrade a Python 3 dove gestiscono l'ordinamento unicode o converti prima le stringhe unicode in stringhe ASCII, usando una comprensione dell'elenco, come questa:
# for Python2, ensure all elements are ASCII (NOT unicode) strings first
x = [str(element) for element in x]
# for Python2, this sort will only work on ASCII (NOT unicode) strings
x.sort(key=str.lower)
Riferimenti:
- https://docs.python.org/3/library/stdtypes.html#list.sort
- Converti una stringa Unicode in una stringa in Python (contenente simboli extra)
- https://www.programiz.com/python-programming/list-comprehension