pythonソートsorted最初の条件が同じ場合は2番目の条件でソート
6573 ワード
検証対象
list
1.
2. 2
a = [[2,3],[4,1],(2,8),(2,1),(3,4)]
b = sorted(a,key=lambda x: (x[0], -x[1]))
print b
a = [[2,{'a':8}],[4,{'a':1}],(2,{'a':8}),(2,{'a':1}),(3,{'a':4})]
array = [7,8]
def fun(x):
return (-x[0],x[1].get('a'))
b = sorted(a,key=fun)
print b
import time
n = xrange(1000000)
x = zip(n, n)
start = time.time()
x.sort(key = lambda x: (x[0], -x[1]))
end = time.time()
print 'key', end-start
x = zip(n, n)
start = time.time()
x.sort(cmp=lambda x, y: x[0] - y[0] or y[1] - x[1])
end = time.time()
print 'cmp', end-start
:
key 2.34500002861 cmp 0.269000053406
key , , , key 。
'-' , :
class Reversinator(object):
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return other.obj < self.obj
a = [(2,'3'),(4,'1'),(2,'8'),(2,'1'),(3,'4')]
print sorted(a, key=lambda x: (x[0], Reversinator(x[1])))
:
Python , , key
list.sort key
key , , key
#python list
def my_key1(x):
return x % 10
aList = [4, 5, 1, 2, 12, 34, 56, 9 ,80]
aList.sort() #
print(aList)
aList.sort(reverse = True) #
print(aList)
aList.sort(key = my_key1) # key ,
print(aList)
def my_key2(x):
return x[1]
aList = [(4,'ab'), (56,'c'), (1,'bb'), (102, 'a')]
aList.sort(key = my_key2) # 2 ,
print(aList)
転載先:https://www.cnblogs.com/rgxx/p/10601772.html