簡體   English   中英

如何獲得具有更高元素總和的列表

[英]How to get the list with the higher sum of its elements

我想知道是否有人可以幫我解決我遇到的Python問題。 我有四個列表,每個列表包含浮點數(小數)。 我正在添加每個列表包含的所有浮點數。 我堅持的部分是我想知道四個列表中哪一個有更高的總和。 我知道我可以使用if語句,但有人知道更多有效的方法。 例如:

foodmart = [12.33,5.55]
nike = [42.20,69.99]
gas_station = [0.89,45.22]
toy_store = [10.99,15.32]

使用max()

>>> max(foodmart,nike,gas_station,toy_store, key=sum)
>>> [42.2, 69.99]

max help()

max(iterable [,key = func]) - > value

max(a,b,c,... [,key = func]) - >值

使用單個可迭代參數,返回其最大項。 使用兩個或多個參數,返回最大的參數。

將列表表示為dict並使用max和可選的key函數來計算sum

不要以你的方式表示列表,而是使用字典。 可以更容易地確定正確的商店並在任何數量的列表/商店上工作,而無需在最大例程中枚舉它們。 這將更加Pythonic和可維護

>>> shops = dict()
>>> shops['foodmart'] = [12.33,5.55]
>>> shops['nike'] = [42.20,69.99]
>>> shops['gas_station'] = [0.89,45.22]
>>> shops['toy_store'] = [10.99,15.32]
>>> max(shops, key = lambda k:sum(shops[k]))
'nike'
>>> max([1,2],[3,4],[2,3], key=lambda x: sum(x))
[3, 4]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM