Python lambda函数下划线-冒号语法说明? [英] Python lambda function underscore-colon syntax explanation?
问题描述
在下面的Python脚本中,"aDict"是字典,在lambda函数中"_:_ [0]"有什么作用?
In the following Python script where "aDict" is a dictionary, what does "_: _[0]" do in the lambda function?
sorted(aDict.items(), key=lambda _: _[0])
推荐答案
让我们分开.
1)假设您有一个字典,di:
1) Suppose you have a dict, di:
di={'one': 1, 'two': 2, 'three': 3}
2)现在,假设您想要其每个键,值对:
2) Now suppose you want each of its key, value pairs:
>>> di.items()
[('three', 3), ('two', 2), ('one', 1)]
3)现在您要对它们进行排序(因为字典是无序的):
3) Now you want to sort them (since dicts are unordered):
>>> sorted(di.items())
[('one', 1), ('three', 3), ('two', 2)]
请注意,元组按字典顺序排序-由元组第一个元素中的文本排序.这等效于一系列元组的t[0]
.
Notice that the tuples are sorted lexicographically -- by the text in the first element of the tuple. This is a equivalent to the t[0]
of a series of tuples.
假设您希望按数字对它进行排序.您将使用key
函数:
Suppose you wanted it sorted by the number instead. You would you use a key
function:
>>> sorted(di.items(), key=lambda t: t[1])
[('one', 1), ('two', 2), ('three', 3)]
您拥有sorted(aDict.items(), key=lambda _: _[0])
的语句只是使用_
作为变量名.它也不执行任何操作,因为aDict.items()
会生成元组,并且如果您不使用键,则无论如何它都将按元组的第一个元素进行排序.您的示例中的关键功能完全没用.
The statement you have sorted(aDict.items(), key=lambda _: _[0])
is just using _
as a variable name. It also does nothing, since aDict.items()
produces tuples and if you did not use a key it sorts by the first element of the tuple anyway. The key function in your example is completely useless.
可能需要考虑该表单的一个用例(元组除外).如果您使用的是字符串,那么您将按第一个字符进行排序,而忽略其余字符:
There might be a use case for the form (other than for tuples) to consider. If you had strings instead, then you would be sorting by the first character and ignoring the rest:
>>> li=['car','auto','aardvark', 'arizona']
>>> sorted(li, key=lambda c:c[0])
['auto', 'aardvark', 'arizona', 'car']
对比:
>>> sorted(li)
['aardvark', 'arizona', 'auto', 'car']
但是我仍然不会在lambda中使用_
. _
的使用是对具有最小机会产生副作用的throway变量的使用. Python的命名空间通常会使这种担心不再是真正的烦恼.
I still would not use _
in the lambda however. The use of _
is for a throway variable that has minimal chance of side-effects. Python has namespaces that mostly makes that worry not a real worry.
考虑:
>>> c=22
>>> sorted(li, key=lambda c:c[0])
['auto', 'aardvark', 'arizona', 'car']
>>> c
22
c
的值得以保留,因为lambda
内有本地名称空间.
The value of c
is preserved because of the local namespace inside the lambda
.
但是(在Python 2.x而非Python 3.x下)可能是一个问题:
However (under Python 2.x but not Python 3.x) this can be a problem:
>>> c=22
>>> [c for c in '123']
['1', '2', '3']
>>> c
'3'
因此,在列表理解或元组扩展等情况下,(轻型)约定开始对变量使用_
,在这种情况下,您不必担心践踏一个名称.消息是:如果将其命名为_
,那么我就不在乎它了.
So the (light) convention became using _
for a variable either in the case of a list comprehension or a tuple expansion, etc where you worry less about trampling on one of your names. The message is: If it is named _
, I don't really care about it except right here...
这篇关于Python lambda函数下划线-冒号语法说明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!