日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python中的?sorted()函數(shù)和sort()方法區(qū)別_python

作者:侯小啾?? ? 更新時(shí)間: 2022-04-16 編程語言

1.sort()

首先看sort()方法,sort方法只能對列表進(jìn)行操作,而sorted可用于所有的可迭代對象。

a = [1, 5, 3, 4, 2]
a.sort()
print(a)

調(diào)用sort()方法后,原列表被改變。

2.sorted()

再看sorted()函數(shù),

sorted(iterable, key=None, reverse=False)

  • iterable是一個(gè)可迭代對象
  • key為指定的排序標(biāo)的,指定排列的是哪一個(gè)值。參數(shù)類型為 函數(shù)類型。(需要傳入一個(gè)函數(shù))
  • 如給dic_items里的鍵值對排序時(shí),默認(rèn)是按照鍵來排,可以設(shè)定此參數(shù)來按照Value排列。
  • reverse為排序方式,F(xiàn)alse為升序,True為降序

返回值是一個(gè)列表。

3.sorted()操作列表

a = [1, 5, 3, 4, 2]
print(sorted(a))
print(a)

使用sorted函數(shù),不改變原列表。
sorted操作其他可迭代對象大致過程同上。

4.sorted()排序字典

使用sorted()排序字典,首先要將字典中的值放在一個(gè)可迭代對象中:
這里將dict1轉(zhuǎn)化為dict1.items()后,再傳入sorted()函數(shù)中即可。

關(guān)于參數(shù)key有兩種常用寫法,

①參數(shù)key:使用lambda定義

使用lambda定義一個(gè)獲取x第二個(gè)值的函數(shù),這里x指可迭代對象中的元素。

dict1 = {'a': 1, 'b': 4, 'c': 2, 'd': 3}
print(sorted(dict1.items(), key=lambda x: x[1], reverse=True))

②參數(shù)key:使用itemgetter直接生成

from operator import itemgetter
dict1 = {'a': 1, 'b': 4, 'c': 2, 'd': 3}
print(sorted(dict1.items(), key=itemgetter(1), reverse=True))

也可以達(dá)到一樣的效果:

關(guān)于itemgetter()是個(gè)什么,itemgetter()是一個(gè)高階函數(shù),返回值是一個(gè)函數(shù),itemgetter(1)等同于lambda x: x[1]。

單獨(dú)對其進(jìn)行調(diào)用就可以看出:

from operator import itemgetter
print(itemgetter(1)([1, 2, 3]))

如圖,其獲取了列表[1, 2, 3]索引為1的值。

原文鏈接:https://blog.csdn.net/weixin_48964486/article/details/122841737

欄目分類
最近更新