嵌套列表上的 min/max 函数如何工作?
How does the min/max function on a nested list work?
比方说,有一个嵌套列表,例如:
my_list = [[1, 2, 21], [1, 3], [1, 2]]
当调用函数 min()
时:
min(my_list)
收到的输出是
[1, 2]
为什么以及如何运作?它有哪些用例?
它按元素比较列表:
>>> [1,2]<[1,3]
True
>>> [1,2]<[1,2,21]
True
>>>
如何在 Python 中比较列表和其他序列?
比较 Python 中的列表(和其他序列)lexicographically,而不是基于任何其他参数。
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.
什么是字典排序?
上的维基百科页面
lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters.
min
函数returnsiterable中的最小值。所以 [1,2]
的字典序值是该列表中最小的。您可以使用 [1,2,21]
进行检查
>>> my_list=[[1,2,21],[1,3],[1,2]]
>>> min(my_list)
[1, 2]
在 min
这种情况下发生了什么?
my_list
上的元素明智,首先是 [1,2,21]
和 [1,3]
。现在来自文档
If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively.
因此 [1,1,21]
的值小于 [1,3]
,因为 [1,3]
的第二个元素,即 3
在字典序上 更高 比 [1,1,21]
的第二个元素的值,即 1
。
现在比较 [1,2]
和 [1,2,21]
,并从文档中添加另一个引用
If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.
[1,2]
是[1,2,21]
的初始子序列。所以[1,2]
的值总体上小于[1,2,21]
的值。因此 [1,2]
作为输出返回。
这可以通过使用 sorted
函数
来验证
>>> sorted(my_list)
[[1, 2], [1, 2, 21], [1, 3]]
如果列表有多个最小元素怎么办?
如果列表包含重复的最小元素返回第一个
>>> my_list=[[1,2],[1,2]]
>>> min(my_list)
[1, 2]
这可以使用 id
函数调用来确认
>>> my_list=[[1,2],[1,2]]
>>> [id(i) for i in my_list]
[140297364849368, 140297364850160]
>>> id(min(my_list))
140297364849368
我需要做什么来防止min
中的字典序比较?
如果需要的比较不是字典那么可以使用key
参数(如所述)
min
函数有一个 额外的可选参数 ,名为 key
。 key
参数接受一个函数。
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)
).
例如,如果我们需要长度最小的元素,我们需要使用len
函数。
>>> my_list=[[1,2,21],[1,3],[1,2]]
>>> min(my_list,key=len) # Notice the key argument
[1, 3]
正如我们所见,这里返回了第一个最短的元素。
如果列表是异构的怎么办?
直到Python2
如果列表是异构的 type names 考虑排序,勾选 Comparisions,
Objects of different types except numbers are ordered by their type names
因此,如果您将 int
和 list
放在那里,您将得到最小的整数值,因为 i
的值低于 l
。同样, '1'
的价值将高于这两者。
>>> my_list=[[1,1,21],1,'1']
>>> min(my_list)
1
Python3 及以上
然而,这种令人困惑的技术在 Python3 中被删除了。它 现在提出 TypeError
。阅读 What's new in Python 3.0
The ordering comparison operators (<
, <=
, >=
, >
) raise a TypeError
exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < ''
, 0 > None
or len <= len
are no longer valid, and e.g. None < None
raises TypeError
instead of returning False
. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other.
>>> my_list=[[1,1,21],1,'1']
>>> min(my_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()
但它适用于可比类型,例如
>>> my_list=[1,2.0]
>>> min(my_list)
1
这里我们可以看到list
包含float
个值和int
个值。但是由于 float
和 int
是可比较的类型,因此 min
函数在这种情况下有效。
两个列表按元素进行比较
即使两个列表的大小不同,也会从第一个元素开始比较两个列表的元素。
现在假设已经检查了列表的每个元素并且它们是相同的并且较短的列表中没有下一个元素。然后声明较短的列表小于较长的列表。
示例:
>>> [1,2]<[1,3]
True
>>> [1,2]<[1,2,21]
True
>>> [1,3]<[1,2,21]
False
>>>[1,2,22]<[1,2,21]
False
>>>[1]<[1,2,21]
True
>>>
字典排序的一个简单用例是制作可排序的 namedtuple
class.
from collections import namedtuple
Time = namedtuple('Time', ['hours', 'minutes', 'seconds'])
t1 = Time(hours=8, minutes=15, seconds=30)
t2 = Time(hours=8, minutes=15, seconds=0)
t3 = Time(hours=8, minutes=30, seconds=30)
t4 = Time(hours=7, minutes=15, seconds=30)
assert min(t1, t2, t3, t4) == t4
assert max(t1, t2, t3, t4) == t3
比方说,有一个嵌套列表,例如:
my_list = [[1, 2, 21], [1, 3], [1, 2]]
当调用函数 min()
时:
min(my_list)
收到的输出是
[1, 2]
为什么以及如何运作?它有哪些用例?
它按元素比较列表:
>>> [1,2]<[1,3]
True
>>> [1,2]<[1,2,21]
True
>>>
如何在 Python 中比较列表和其他序列?
比较 Python 中的列表(和其他序列)lexicographically,而不是基于任何其他参数。
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.
什么是字典排序?
上的维基百科页面lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters.
min
函数returnsiterable中的最小值。所以 [1,2]
的字典序值是该列表中最小的。您可以使用 [1,2,21]
>>> my_list=[[1,2,21],[1,3],[1,2]]
>>> min(my_list)
[1, 2]
在 min
这种情况下发生了什么?
my_list
上的元素明智,首先是 [1,2,21]
和 [1,3]
。现在来自文档
If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively.
因此 [1,1,21]
的值小于 [1,3]
,因为 [1,3]
的第二个元素,即 3
在字典序上 更高 比 [1,1,21]
的第二个元素的值,即 1
。
现在比较 [1,2]
和 [1,2,21]
,并从文档中添加另一个引用
If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.
[1,2]
是[1,2,21]
的初始子序列。所以[1,2]
的值总体上小于[1,2,21]
的值。因此 [1,2]
作为输出返回。
这可以通过使用 sorted
函数
>>> sorted(my_list)
[[1, 2], [1, 2, 21], [1, 3]]
如果列表有多个最小元素怎么办?
如果列表包含重复的最小元素返回第一个
>>> my_list=[[1,2],[1,2]]
>>> min(my_list)
[1, 2]
这可以使用 id
函数调用来确认
>>> my_list=[[1,2],[1,2]]
>>> [id(i) for i in my_list]
[140297364849368, 140297364850160]
>>> id(min(my_list))
140297364849368
我需要做什么来防止min
中的字典序比较?
如果需要的比较不是字典那么可以使用key
参数(如
min
函数有一个 额外的可选参数 ,名为 key
。 key
参数接受一个函数。
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)
).
例如,如果我们需要长度最小的元素,我们需要使用len
函数。
>>> my_list=[[1,2,21],[1,3],[1,2]]
>>> min(my_list,key=len) # Notice the key argument
[1, 3]
正如我们所见,这里返回了第一个最短的元素。
如果列表是异构的怎么办?
直到Python2
如果列表是异构的 type names 考虑排序,勾选 Comparisions,
Objects of different types except numbers are ordered by their type names
因此,如果您将 int
和 list
放在那里,您将得到最小的整数值,因为 i
的值低于 l
。同样, '1'
的价值将高于这两者。
>>> my_list=[[1,1,21],1,'1']
>>> min(my_list)
1
Python3 及以上
然而,这种令人困惑的技术在 Python3 中被删除了。它 现在提出 TypeError
。阅读 What's new in Python 3.0
The ordering comparison operators (
<
,<=
,>=
,>
) raise aTypeError
exception when the operands don’t have a meaningful natural ordering. Thus, expressions like1 < ''
,0 > None
orlen <= len
are no longer valid, and e.g.None < None
raisesTypeError
instead of returningFalse
. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other.
>>> my_list=[[1,1,21],1,'1']
>>> min(my_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()
但它适用于可比类型,例如
>>> my_list=[1,2.0]
>>> min(my_list)
1
这里我们可以看到list
包含float
个值和int
个值。但是由于 float
和 int
是可比较的类型,因此 min
函数在这种情况下有效。
两个列表按元素进行比较
即使两个列表的大小不同,也会从第一个元素开始比较两个列表的元素。
现在假设已经检查了列表的每个元素并且它们是相同的并且较短的列表中没有下一个元素。然后声明较短的列表小于较长的列表。
示例:
>>> [1,2]<[1,3]
True
>>> [1,2]<[1,2,21]
True
>>> [1,3]<[1,2,21]
False
>>>[1,2,22]<[1,2,21]
False
>>>[1]<[1,2,21]
True
>>>
字典排序的一个简单用例是制作可排序的 namedtuple
class.
from collections import namedtuple
Time = namedtuple('Time', ['hours', 'minutes', 'seconds'])
t1 = Time(hours=8, minutes=15, seconds=30)
t2 = Time(hours=8, minutes=15, seconds=0)
t3 = Time(hours=8, minutes=30, seconds=30)
t4 = Time(hours=7, minutes=15, seconds=30)
assert min(t1, t2, t3, t4) == t4
assert max(t1, t2, t3, t4) == t3