Sort list of strings ignoring upper/lower case

不羁岁月 提交于 2019-11-28 06:24:25

The sort() method and the sorted() function take a key argument:

var.sort(key=lambda v: v.upper())

The function named in key is called for each value and the return value is used when sorting, without affecting the actual values:

>>> var=['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
>>> sorted(var, key=lambda v: v.upper())
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']

To sort Ant before ant, you'd have to include a little more info in the key, so that otherwise equal values are sorted in a given order:

>>> sorted(var, key=lambda v: (v.upper(), v[0].islower()))
['Ant', 'ant', 'Bat', 'bat', 'Cat', 'cat', 'Goat', 'Lion']

The more complex key generates ('ANT', False) for Ant, and ('ANT', True) for ant; True is sorted after False and so uppercased words are sorted before their lowercase equivalent.

See the Python sorting HOWTO for more information.

New answer for Python 3, I'd like to add two points:

  1. Use str.casefold for case-insensitive comparisons.
  2. Use the method directly instead of inside of a lambda.

That is:

var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']

var.sort(key=str.casefold)

(which sorts in-place) and now:

>>> var
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']

Or, to return a new list, use sorted

>>> var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
>>> sorted(var, key=str.casefold)
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']

Why is this different from str.lower or str.upper? According to the documentation:

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, str.lower() would do nothing to 'ß'; casefold() converts it to "ss".

Ahmed

We can use the 'sorted' function according to Python Sorting HOW TO documentation.

a = sorted(Input, key=str.lower)print("Output1: ",a)

Output1:

['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!