2

我想知道是否有人可以帮助我解决我遇到的 Python 问题。我有四个列表,每个列表都包含浮点数(小数)。我正在添加每个列表包含的所有浮点数。我坚持的部分是我想知道四个列表中哪一个的总和更高。我知道我可以使用 if 语句,但有谁知道更有效的方法。例如:

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

3 回答 3

7

使用max()

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

help()max

最大值(可迭代 [,键 = 函数])-> 值

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

使用单个可迭代参数,返回其最大的项目。使用两个或更多参数,返回最大的参数。

于 2013-01-10T16:09:21.467 回答
4

将列表表示为 adictmax与可选key函数一起使用来计算sum

不要以您的方式表示列表,而是使用字典。确定正确的商店并处理任意数量的列表/商店会更容易,而无需在 max 例程中枚举它们。这将更加 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'
于 2013-01-10T16:13:26.583 回答
2
>>> max([1,2],[3,4],[2,3], key=lambda x: sum(x))
[3, 4]
于 2013-01-10T16:08:51.840 回答