[英]Python Sorting Lists in Lists
Given: lst = [['John',3],['Blake',4],['Ted',3]]
给定: lst = [['John',3],['Blake',4],['Ted',3]]
Result: lst = [['John',3],['Ted',3],['Blake',4]]
结果: lst = [['John',3],['Ted',3],['Blake',4]]
I'm looking for a way to sort lists in lists first numerically then alphabetically without the use of the "itemgetter" syntax. 我正在寻找一种在不使用“ itemgetter”语法的情况下先按数字顺序然后按字母顺序对列表中的列表进行排序的方法。
由于您坚持:
lst.sort(key=lambda x: x[::-1])
You could use the argument key
from the built-in sorted
function. 您可以使用内置sorted
函数中的参数key
。
In this key
argument, you pass a function with one parameter, that returns something that will be sorted instead of sorting the list by its elements. 在此key
参数中,您传递了一个带有一个参数的函数,该函数返回将进行排序的内容,而不是按其元素对列表进行排序。
def my_func(elem):
# return a tuple (second element, first element)
return (elem[1], elem[0])
>>> lst = [['John',3],['Blake',4],['Ted',3]]
>>> sorted(lst, key=my_func)
[['John', 3], ['Ted', 3], ['Blake', 4]]
Or even shorter: 甚至更短:
>>> sorted(lst, key=lambda x: (x[1],x[0]))
[['John', 3], ['Ted', 3], ['Blake', 4]]
In both ways, you sort first numerically, then alphabetically. 在这两种方式中,您都首先按数字排序,然后按字母顺序排序。
I think this may have been asked before in the following question: 我认为这可能是在以下问题之前提出的:
Sorting a list of lists in Python 在Python中对列表列表进行排序
Here is the explanation given by Dave Webb: 这是Dave Webb给出的解释:
The key
argument to sort
specifies a function of one argument that is used to extract a comparison key from each list element. 要sort
的key
参数指定一个参数的功能,该参数用于从每个列表元素中提取比较键。 So we can create a simple lambda
that returns the last element from each row to be used in the sort: 因此,我们可以创建一个简单的lambda
,该lambda
返回每行要使用的最后一个元素:
c2.sort(key = lambda row: row[2])
A lambda
is a simple anonymous function. lambda
是一个简单的匿名函数。 It's handy when you want to create a simple single use function like this. 当您要创建一个像这样的简单一次性功能时,它很方便。 The equivalent code not using a lambda
would be: 不使用lambda
的等效代码为:
def sort_key(row):
return row[2]
c2.sort(key = sort_key)
If you want to sort on more entries, just make the key
function return a tuple containing the values you wish to sort on in order of importance. 如果要对更多条目进行排序,只需使key
函数返回一个元组,其中包含要按重要性顺序排序的值。 For example: 例如:
c2.sort(key = lambda row: (row[2],row[1]))
or: 要么:
c2.sort(key = lambda row: (row[2],row[1],row[0]))
What's wrong with itemgetter? itemgetter有什么问题?
lst.sort(key=lambda l: list(reversed(l))
should do the trick lst.sort(key=lambda l: list(reversed(l))
应该可以解决问题
In Python2, you can use this 在Python2中,您可以使用此
>>> lst = [['John',3],['Blake',4],['Ted',3]]
>>> lst.sort(key=sorted)
>>> lst
[['John', 3], ['Ted', 3], ['Blake', 4]]
This works because ints are always "less than" strings in Python2 这是可行的,因为在Python2中int始终是“小于”字符串
You can no longer sort str
and int
objects in Python3 though 不过,您无法再在Python3中对str
和int
对象进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.