1. 程式人生 > >嵌套列表排序,指定排序

嵌套列表排序,指定排序

內置函數 int 嵌套 獲取對象 span tor python imp 輸入

方法一 : 使用python的內置函數

# 方法 1
import operator
inventory = [(apple, 3), (banana, 2), (pear, 5), (orange, 1)]
inventory.sort(key=operator.itemgetter(1))
print(inventory)

n = operator.itemgetter(1)  # 定義函數n,獲取對象的第1個域的值
print(n(inventory))  # 輸入參數
n = operator.itemgetter(1,2)  # 定義函數n,獲取對象的第1.2個域的值
print(n(inventory))

結果

[(orange, 1), (banana, 2), (apple, 3), (pear, 5)]
(banana, 2)
((banana, 2), (apple, 3))

方法2 使用匿名函數

# 方法 2
inventory = [(apple, 3), (banana, 2), (pear, 5), (orange, 1)]
inventory.sort(key= lambda x:x[1])
print(inventory)

結果

[(orange, 1), (banana
, 2), (apple, 3), (pear, 5)]

嵌套列表排序,指定排序