gpt4 book ai didi

python - 基于乱序比较将列表与 min() 进行比较

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:45 25 4
gpt4 key购买 nike

我有一个列表列表,例如 q = [[1,2],[3,4]],其中每个子列表都是 2 个整数的列表,我返回每个 extreme point 的索引(我想?)。

我需要的是列表的索引,其中第二个条目中的最小值/最大值在子列表的所有第二个条目中,如果第二个条目中有其他具有相同值的子列表,则索引为返回最小/最大第二值条目列表中的最小/最大第一个值。

例如,如果 q = [[1, 2], [3, 4], [1, 0], [0, 5]],我需要 min 秒,如果平局,然后是 min second,然后是 first。所以我需要 min(S) 来返回 [1,0]。相反,它似乎返回的是 [0,5]

>>> q = [[1,2],[3,4]]
>>> min(q)
[1, 2]
>>> q.append([1,0])
>>> min(q)
[1, 0]
>>> q.append([0,5])
>>> min(q)
[0, 5]
>>> q
[[1, 2], [3, 4], [1, 0], [0, 5]]

根据 this answer here ,比较列表按元素的顺序比较它们,使用下一个列表条目作为决胜局。

>>> q.append([0,6])
>>> q.append([0,4])
>>> min(q)
[0, 4]
>>> q
[[1, 2], [3, 4], [1, 0], [0, 5], [0, 6], [0, 4]]
>>>

有什么方法可以控制比较中的顺序吗?我试着通读 documentation ,但我不明白我在读什么。

最佳答案

使用 [min()](1] 的 key 关键字参数:

示例:

>>> from operator import itemgetter
>>> q = [[1, 2], [3, 4], [1, 0], [0, 5]]
>>> min(q, key=itemgetter(1, 0))
[1, 0]

这将通过关键函数 itemgetter(1, 0) 对可迭代的 q 进行排序,该函数基本上返回 ( 2nd-item, 1st-item) 并且等价于 min(q, key=lambda x: (x[1], x[0]))

min(iterable[, key]) min(arg1, arg2, *args[, key])\

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).

Changed in version 2.5: Added support for the optional key argument.

关于python - 基于乱序比较将列表与 min() 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30747248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com