我从已排序的 CSV 文件中创建了以下列表。
list1 = sorted(csv1, key=operator.itemgetter(1))
我想按照两个条件对列表进行排序:首先是根据第一个字段的值,然后再根据第二个字段的值。我该如何做到这一点?
在使用lambda函数时,无需导入任何内容。
以下代码按第一个元素排序,然后按第二个元素排序。您还可以按一个字段升序和另一个字段降序排序,例如:
sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))
-
在-x[1]
中代表取相反数的意思。 - jan像这样:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
operator
是一个需要导入的模块。 - trapickiPython有一个稳定的排序算法,所以只要性能不是问题,最简单的方法就是先按第二个字段进行排序,然后再按第一个字段进行排序。
这将给您想要的结果,唯一的问题是,如果列表很大(或者您想经常进行排序),两次调用排序可能会导致过高的开销。
list1 = sorted(csv1, key=operator.itemgetter(2))
list1 = sorted(list1, key=operator.itemgetter(1))
这种方法也使得处理需要对某些列进行反向排序的情况变得容易,只需在必要时包含'reverse=True'参数即可。DATA = [
('Jones', 'Jane', 58),
('Smith', 'Anne', 30),
('Jones', 'Fred', 30),
('Smith', 'John', 60),
('Smith', 'Fred', 30),
('Jones', 'Anne', 30),
('Smith', 'Jane', 58),
('Smith', 'Twin2', 3),
('Jones', 'John', 60),
('Smith', 'Twin1', 3),
('Jones', 'Twin1', 3),
('Jones', 'Twin2', 3)
]
# Sort by Surname, Age DESCENDING, Firstname
print("Initial data in random order")
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
print('''
First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred''')
DATA.sort(key=lambda row: row[1])
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
print('''
Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.''')
DATA.sort(key=lambda row: row[2], reverse=True)
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
print('''
Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.
''')
DATA.sort(key=lambda row: row[0])
for d in DATA:
print("{:10s} {:10s} {}".format(*d))
以下是可运行的示例,但为了避免让人们运行它,输出结果已省略:
Initial data in random order
Jones Jane 58
Smith Anne 30
Jones Fred 30
Smith John 60
Smith Fred 30
Jones Anne 30
Smith Jane 58
Smith Twin2 3
Jones John 60
Smith Twin1 3
Jones Twin1 3
Jones Twin2 3
First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred
Smith Anne 30
Jones Anne 30
Jones Fred 30
Smith Fred 30
Jones Jane 58
Smith Jane 58
Smith John 60
Jones John 60
Smith Twin1 3
Jones Twin1 3
Smith Twin2 3
Jones Twin2 3
Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.
Smith John 60
Jones John 60
Jones Jane 58
Smith Jane 58
Smith Anne 30
Jones Anne 30
Jones Fred 30
Smith Fred 30
Smith Twin1 3
Jones Twin1 3
Smith Twin2 3
Jones Twin2 3
Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.
Jones John 60
Jones Jane 58
Jones Anne 30
Jones Fred 30
Jones Twin1 3
Jones Twin2 3
Smith John 60
Smith Jane 58
Smith Anne 30
Smith Fred 30
Smith Twin1 3
Smith Twin2 3
请特别注意第二步中reverse=True
参数的使用,它保持了firstname的顺序,而如果只是先排序再反转列表,则会失去对第三个排序关键字所需的顺序。
list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )
turple()
函数不能接收两个参数(或者更确切地说,三个参数,如果你算上self
的话)。 - Filipe Correiareturn
语句应该是 return tuple((x[1], x[2]))
或者简单地写成 return x[1], x[2]
。如果你想要按不同的方向进行排序,请参考下面的 @jaap 的答案。 - Jo Kachikaranx[1],x[2]
,那么可以使用tuple(x[1:3])
。或者使用keyfunc = operator.itemgetter(1, 2)
,甚至不需要自己编写一个函数。 - abarnertlist1 = sorted(csv1, key=lambda x: x[1] and x[2])
?如果不行,那么在这种情况下会出现什么行为? - ahmetbulutemployees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])
x [1]
对列表进行排序。然后,它将按照第一个元素x [0]
进行排序(最高优先级)。employees[0] = "Employee's Name"
employees[1] = "Employee's Salary"
employees.sort(key = lambda x:(x[0], x[1]))
使用下面的方法对字典列表进行排序,会按照工资作为第一列和年龄作为第二列进行降序排序。
d=[{'salary':123,'age':23},{'salary':123,'age':25}]
d=sorted(d, key=lambda i: (i['salary'], i['age']),reverse=True)
输出:[{'salary': 123, 'age': 25}, {'salary': 123, 'age': 23}]
[[1,2],[3,3],[2,1],[1,1],[4,1],[3,1]]
,期望输出为:[[4, 1], [3, 1], [3, 3], [2, 1], [1, 1], [1, 2]]
,代码如下: arr = [[1,2],[3,3],[2,1],[1,1],[4,1],[3,1]]
arr.sort(key=lambda ele: (ele[0], -ele[1]), reverse=True)
# output [[4, 1], [3, 1], [3, 3], [2, 1], [1, 1], [1, 2]]
在阅读了本主题中的答案后,我编写了一个通用解决方案,适用于任意数量的列:
def sort_array(array, *columns):
for col in columns:
array.sort(key = lambda x:x[col])
OP会这样调用它:
sort_array(list1, 2, 1)
您可以使用以下升序:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))
或者按降序排列可以使用:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)
Python 3
https://docs.python.org/3.5/howto/sorting.html#the-old-way-using-the-cmp-parameterfrom functools import cmp_to_key
def custom_compare(x, y):
# custom comparsion of x[0], x[1] with y[0], y[1]
return 0
sorted(entries, key=lambda e: (cmp_to_key(custom_compare)(e[0]), e[1]))
__lt __()
方法或继承一些已经定义了该方法的类”?那将使它成为一个更好的规范。 - smci