排序常用方法

  • 列表內(nèi)置函數(shù)sort
# sort是會(huì)影響列表本身
lis = [4,5,68,46,4,]
lis.sort()
print(lis)
[4, 4, 5, 46, 68]

sorted

  • 字典排序
dic = {0: 9, 1: 0, 2: 3, 3: 3, 4: 1, 5: 7, 6: 4}
# 將字典items鍵值對組成元組傳入,取每個(gè)元組[1]元素進(jìn)行排序,reverse表示升降序
b = dict(sorted(dic.items(),key=lambda x:x[1],reverse=True))
print(b)
{0: 9, 5: 7, 6: 4, 2: 3, 3: 3, 4: 1, 1: 0}
  • 列表內(nèi)嵌字典
portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

a = sorted([i for i in portfolio],key=lambda x:x['price'],reverse=True)

print(a)
  • 模塊heapq方法
    • 傳入三個(gè)參數(shù), nsmallest(n, iterable, key=None)
    • n -> 排序的數(shù)量
    • iterable -> 要排序的可迭代對象
    • key -> 排序的關(guān)鍵字
import heapq

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
# 升序

cheap = heapq.nsmallest(len(portfolio),portfolio, key=lambda s: s['price'])
print(cheap)
[{'name': 'YHOO', 'price': 16.35, 'shares': 45},
 {'name': 'FB', 'price': 21.09, 'shares': 200},
 {'name': 'HPQ', 'price': 31.75, 'shares': 35},
 {'name': 'IBM', 'price': 91.1, 'shares': 100},
 {'name': 'ACME', 'price': 115.65, 'shares': 75},
 {'name': 'AAPL', 'price': 543.22, 'shares': 50}]

# 降序
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
print(expensive)
[{'name': 'AAPL', 'price': 543.22, 'shares': 50},
 {'name': 'ACME', 'price': 115.65, 'shares': 75},
 {'name': 'IBM', 'price': 91.1, 'shares': 100}]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容