基于无序比较将列表与min()进行比较

2024-06-28 20:38:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

例如,如果q = [[1, 2], [3, 4], [1, 0], [0, 5]],我需要minsecond,如果tie,那么minsecond,然后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,但我不明白我在读什么。你知道吗


Tags: answer元素列表here顺序条目整数min
3条回答

可以使用扩展切片语法反转子列表:

>>> q = [[1, 2], [3, 4], [1, 0], [0, 5]]
>>> min(q, key=lambda sl: sl[::-1])
[1, 0]

这对你有用吗?你知道吗

min(q, key = lambda x: (x[1],x[0]))

使用[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)对可iteable q进行排序,该键函数基本上返回tuple(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.

相关问题 更多 >