假設有字典列表:
dict_list = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}, {'price': 77, 'barcode': '2342377'}]
要求price
的最大值與最小值
最原始的方法:
min_price, max_price = 100, 0
for item in dict_list:
if item['price'] < min_price:
min_price = item['price']
if item['price'] > max_price:
max_price = item['price']
print(max_price, min_price)
剛學Python時會這么寫...
先使用列表推導式(list comprehension), 再使用內置函數求最大值最小值:
seq = [item['price'] for item in dict_list]
print(max(seq), min(seq))
這種方式要遍歷列表多次.
使用生成器表達式(generator expression)
min_price, max_price = 100, 0
for x in (item['the_key'] for item in dict_list):
min_price,max_price = min(x,min_price),max(x,max_price)
print(max_price, min_price)
更簡單的寫法:
max_price = max(item['price'] for item in dict_list)
min_price = min(item['price'] for item in dict_list)
print(max_price, min_price)
This avoids the overhead of sorting the list -- and, by using a generator expression, instead of a list comprehension -- actually avoids creating any lists, as well. Efficient, direct, readable... Pythonic!
返回整個dict, 不僅僅是price:
max_priced_item = max(dict_list, key=lambda x:x['price'])
min_priced_item = min(dict_list, key=lambda x:x['price'])
print(max_priced_item, min_priced_item)
# {'price': 99, 'barcode': '2342355'} {'price': 77, 'barcode': '2342377'}
總結自: In List of Dicts, find min() value of a common Dict field
源網頁: 百度快照