[英]How to get max value and min value of a given list into tuple form with out using built in max and min function from python
[英]How to get the min/max in a list by using a lambda or function to get a comparison value from the item?
在Python中,我想使用lambda在列表中找到max元素進行比較。
這段代碼沒有成功:
# An 'anonymous' object, like JSON object. Use like: Mock(name='Bob', age=30)
class Mock(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
items = [
Mock(cost=10, quantity=1),
Mock(cost=15, quantity=3),
Mock(cost=20, quantity=5),
Mock(cost=100, quantity=2)
]
index, value = max(items, key=lambda(item) : item.cost * item.quantity)
print('$%d, q=%d' % (value.cost, value.quantity))
我收到此錯誤:
index, value = max(items, key=lambda(item) : item.cost * item.quantity)
TypeError: 'Mock' object is not iterable
我該如何正確實現?
如果您不需要索引,可以直接使用結果:
value = max(items, key=lambda(item) : item.cost * item.quantity)
print value.cost, value.quantity
max
返回實際的max項,這是一個Mock
實例。 您無法將其解壓縮為兩個項目。
如果你真的想要索引,你可以找到它,或者稍微修改你的搜索以將索引裝飾到項目中:
index, value = max(enumerate(items), key=lambda(item): item[1].cost * item[1].quantity)
首先,我們將原始列表轉換為第二個列表,其中每個項目都是(索引,值)的元組。 然后,鍵也必須更改,因為item
而不是item.cost
,現在是一個(index, MockItem)
對,所以你需要獲取item[1]
,然后獲取屬性。 不要忘記將結果解壓縮到索引和值以獲得兩者。
這不是最有效的方式,但閱讀它的人很容易理解。 如果您有非常大的列表,請告訴我,我會向您指出更有效的解決方案。
# get the value
max_item = max(items, key=lambda item: item.cost * item.quantity)
# get the index
max_item_index = items.index(max_item)
如果您還想要計算的值,那么只需執行循環以保持清晰:
max_value = max_index = max_item = None
for i, item in enumerate(items):
value = item.cost * item.quantity
if (max_value is None) or (value > max_value):
max_value = value
max_index = i
max_item = item
if max_value is not None:
print max_index, max_value, max_item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.