茨の道も一歩から

インフラ構築からプログラミング(Python・JavaScript)までITに関するブログです。

Python入門:ソート

ソート

逆文字列

'This is a example.'[::-1]

'.elpmaxe a si sihT'

sorted関数

sorted(iterable[, key][, reverse])

odds = [1, 5, 3, 9, 7]
sorted(odds)
[1, 3, 5, 7, 9]

sorted(odds, reverse=True)
[9, 7, 5, 3, 1]

#### 複数キーで1項目で昇順、同値があれば第二項で降順にする
O = {1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}
print(sorted([(k,v) for k,v in O.items() if k in A], key=lambda x: (x[1], -x[0])))

dict

dict = {'banana': 150, 'apple': 200, 'orange': 120, 'chery': 180}

dict.items() # [('orange', 120), ('chery', 180), ('banana', 150), ('apple', 200)]
sorted(dict.items()) # [('apple', 200), ('banana', 150), ('chery', 180), ('orange', 120)]
sorted(dict.items(), key=lamdba x: x[1]) # [('orange', 120), ('banana', 150), ('chery', 180), ('apple', 200)]

vs = lamdba x: x[1]

def valSort(x):
    return x[1]

valSort(('apple', 200)) # 200
vs(('apple', 200)) # 200