忽略大/小写的字符串列表排序(Sort list of strings ignoring upper

2019-07-05 23:04发布

我有一个包含代表动物名称的字符串列表。 我需要对列表进行排序。 如果我使用sorted(list) ,它会给与大写的字符串,然后再小写列表输出。

但我需要下面的输出。

输入:

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

输出:

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

Answer 1:

sort()方法和sorted()函数迈出了关键的参数:

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

在命名的功能key被每值和排序时,在不影响实际值的返回值时:

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

排序Ant之前ant ,你必须包括在关键的一点更多的信息,所以,否则等于值在一个给定的顺序排序:

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

更复杂的密钥生成('ANT', False)用于Ant ,和('ANT', True)用于ant ; True后排序False等大写的单词的小写形式之前排序。

见Python的排序HOWTO了解更多信息。



Answer 2:

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".



Answer 3:

我们可以根据Python的排序如何documentation使用“排序”功能。

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

输出1:

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


文章来源: Sort list of strings ignoring upper/lower case