Python標準庫學(xué)習(xí)之operator.itemgetter函數(shù)的使用
一、簡介
operator.itemgetter
是 Python 標準庫 operator
模塊中的一個函數(shù)。它主要用于獲取可迭代對象中的特定元素,常用于排序操作。這個函數(shù)返回一個可調(diào)用對象,可以方便地從序列或映射中獲取指定的項。
二、語法和參數(shù)
operator.itemgetter(*items)
參數(shù):
*items
:一個或多個索引、鍵或其他可用于從對象中獲取項的值。
三、實例
3.1 基本使用
代碼:
from operator import itemgetter # 創(chuàng)建一個列表 fruits = ['apple', 'banana', 'cherry', 'date'] # 使用itemgetter獲取特定位置的元素 getter = itemgetter(1, 3) result = getter(fruits) print("原始列表:") print(fruits) print("\nitemgetter(1, 3)的結(jié)果:") print(result)
輸出:
原始列表:
['apple', 'banana', 'cherry', 'date']itemgetter(1, 3)的結(jié)果:
('banana', 'date')
3.2 用于列表排序
代碼:
from operator import itemgetter # 創(chuàng)建一個包含元組的列表 people = [ ('John', 25, 'USA'), ('Jane', 30, 'UK'), ('Bob', 22, 'Canada'), ('Alice', 28, 'Australia') ] # 按年齡排序 sorted_by_age = sorted(people, key=itemgetter(1)) print("原始列表:") print(people) print("\n按年齡排序后的列表:") print(sorted_by_age) # 按國家排序,然后按年齡排序 sorted_complex = sorted(people, key=itemgetter(2, 1)) print("\n按國家排序,然后按年齡排序的列表:") print(sorted_complex)
輸出:
原始列表:
[('John', 25, 'USA'), ('Jane', 30, 'UK'), ('Bob', 22, 'Canada'), ('Alice', 28, 'Australia')]按年齡排序后的列表:
[('Bob', 22, 'Canada'), ('John', 25, 'USA'), ('Alice', 28, 'Australia'), ('Jane', 30, 'UK')]按國家排序,然后按年齡排序的列表:
[('Alice', 28, 'Australia'), ('Bob', 22, 'Canada'), ('Jane', 30, 'UK'), ('John', 25, 'USA')]
3.3 用于字典排序
代碼:
from operator import itemgetter # 創(chuàng)建一個字典 fruits = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4} # 按值排序 sorted_by_value = sorted(fruits.items(), key=itemgetter(1)) print("原始字典:") print(fruits) print("\n按值排序后的列表:") print(sorted_by_value) # 轉(zhuǎn)換回字典 sorted_dict = dict(sorted_by_value) print("\n排序后的字典:") print(sorted_dict)
輸出:
原始字典:
{'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}按值排序后的列表:
[('banana', 1), ('cherry', 2), ('apple', 3), ('date', 4)]排序后的字典:
{'banana': 1, 'cherry': 2, 'apple': 3, 'date': 4}
四、注意事項
itemgetter
返回的是一個可調(diào)用對象,不是實際的值。- 對于字典,
itemgetter(key)
等同于lambda x: x[key]
,但性能更好。 - 在處理大量數(shù)據(jù)時,
itemgetter
通常比 lambda 函數(shù)更高效。 itemgetter
可以接受多個參數(shù),用于同時獲取多個項。- 在排序復(fù)雜結(jié)構(gòu)(如包含多個字段的對象列表)時,
itemgetter
特別有用。 - 使用
itemgetter
時要確保指定的鍵或索引在所有要處理的對象中都存在,否則會引發(fā)KeyError
或IndexError
。
到此這篇關(guān)于Python標準庫學(xué)習(xí)之operator.itemgetter函數(shù)的使用的文章就介紹到這了,更多相關(guān)Python operator.itemgetter函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決windows下Sublime Text 2 運行 PyQt 不顯示的方法分享
問題描述:PyQt 環(huán)境正常,可以使用 Windows 的 虛擬 DOS 正常運行,但在 Sublime Text 2 下使用 Ctrl + B 運行后,界面不顯示,但查看任務(wù)管理器,有 python.exe 進程。2014-06-06python使用cartopy庫繪制臺風(fēng)路徑代碼
大家好,本篇文章主要講的是python使用cartopy庫繪制臺風(fēng)路徑代碼,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02四種Python機器學(xué)習(xí)超參數(shù)搜索方法總結(jié)
在建模時模型的超參數(shù)對精度有一定的影響,而設(shè)置和調(diào)整超參數(shù)的取值,往往稱為調(diào)參。本文將演示在sklearn中支持的四種基礎(chǔ)超參數(shù)搜索方法,需要的可以參考一下2022-11-11Python機器學(xué)習(xí)之預(yù)測黃金價格
這篇文章主要介紹了如何使用機器學(xué)習(xí)方法來預(yù)測最重要的貴金屬之一黃金的價格,文中的示例代碼講解詳細,感興趣的小伙伴可以試一試2022-01-01