我有以下值列表列表,我想在所有值中找到最小值。
Q = [[8.85008011807927, 4.129896248976861, 5.556804136197901],
[8.047707185696948, 7.140707521433818, 7.150610818529693],
[7.5326340018228555, 7.065307672838521, 6.862894377422498]]
我打算做这样的事情:
min(min(Q))
我在一个较小的示例中尝试了这种方法并且它有效:
>>>b = [[2,2],[1,9]]
>>>min(b)
[1, 9]
>>>min(min(b))
1
但是在我的原始列表 Q 上使用它会返回错误的结果:
>>> min(Q)
[7.5326340018228555, 7.065307672838521, 6.862894377422498]
>>> min(min(Q))
6.862894377422498
为什么这种方法是错误的,为什么?
最佳答案
使用 lexicographical order 比较列表1(即比较第一个元素,然后是第二个,然后是第三个,依此类推),所以只是因为 list_a < list_b
并不意味着 list_a
中的最小元素小于 list_b
中的最小元素,这就是为什么您的方法在一般情况下不起作用的原因。
例如,考虑一下:
>>> l1 = [3, 0]
>>> l2 = [2, 1]
>>>
>>> min(l1, l2)
[2, 1]
原因min(l1, l2)
是[2, 1]
是因为 l1
的第一个元素( 3
) 最初与 l2
的比较(2
)。现在,2 < 3
, 所以 l2
作为最小值返回,无需任何进一步比较。然而,它是l1
确实包含两个列表中的最小数字 ( 0
),它出现在初始元素之后。因此,取 min
的 min(l1, l2)
给我们错误的结果 1
.
解决这个问题的一个好方法是找到“扁平化”列表的最小值,这可以通过生成器获得:
>>> Q = [[8.85008011807927, 4.129896248976861, 5.556804136197901],
... [8.047707185696948, 7.140707521433818, 7.150610818529693],
... [7.5326340018228555, 7.065307672838521, 6.862894377422498]]
>>>
>>> min(a for sub in Q for a in sub) # <--
4.129896248976861
(+1 给@Ffisegydd,以便首先按照这些思路发布解决方案。)
1 来自 http://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types :
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.
关于python - 了解用于在列表列表中查找最小值的 python 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22098902/