Python在列表中排序列表
给定:Python在列表中排序列表,python,list,Python,List,给定:lst=[[John',3],[Blake',4],[Ted',3] 结果:lst=[[John',3],[Ted',3],[Blake',4]] 我正在寻找一种方法,在列表中对列表进行排序,先按数字排序,然后按字母排序,而不使用“itemgetter”语法。因为您坚持: lst.sort(key=lambda x: x[::-1]) itemgetter怎么了 lst.sort(key=lambda l:list(reversed(l))应该可以做到这一点您可以使用内置的sorted函
lst=[[John',3],[Blake',4],[Ted',3]
结果:lst=[[John',3],[Ted',3],[Blake',4]]
我正在寻找一种方法,在列表中对列表进行排序,先按数字排序,然后按字母排序,而不使用“itemgetter”语法。因为您坚持:
lst.sort(key=lambda x: x[::-1])
itemgetter怎么了
lst.sort(key=lambda l:list(reversed(l))
应该可以做到这一点您可以使用内置的sorted
函数中的参数key
在这个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]]
甚至更短:
>>> sorted(lst, key=lambda x: (x[1],x[0]))
[['John', 3], ['Ted', 3], ['Blake', 4]]
在这两种方式中,您首先按数字排序,然后按字母顺序排序。我想这可能是以前在以下问题中提出的问题: 以下是Dave Webb给出的解释: 指定一个参数的函数,该参数用于从每个列表元素中提取比较键。因此,我们可以创建一个简单的
lambda
,返回排序中要使用的每行的最后一个元素:
c2.sort(key = lambda row: row[2])
当您想要创建这样一个简单的一次性函数时,它非常方便。不使用lambda
的等效代码是:
def sort_key(row):
return row[2]
c2.sort(key = sort_key)
如果要对更多条目进行排序,只需使键
函数返回一个元组,其中包含要按重要性排序的值。例如:
c2.sort(key = lambda row: (row[2],row[1]))
或:
在Python2中,您可以使用
>>> lst = [['John',3],['Blake',4],['Ted',3]]
>>> lst.sort(key=sorted)
>>> lst
[['John', 3], ['Ted', 3], ['Blake', 4]]
这是因为在Python2中int总是“小于”字符串
在Python3中,您不能再对
str
和int
对象进行排序,尽管我认为Python建议在之前使用sorted()
>>> lst = [['John',3],['Blake',4],['Ted',3]]
>>> lst.sort(key=sorted)
>>> lst
[['John', 3], ['Ted', 3], ['Blake', 4]]