Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 相同的内置函数_Python_Python 3.x - Fatal编程技术网

Python 相同的内置函数

Python 相同的内置函数,python,python-3.x,Python,Python 3.x,Python3中是否有用于函数lambda x:x的内置函数?有时它可能会使一些代码更优雅。例如: def my_sort(lst, key): ... lst = [4, 3, 7, 1, 9] my_sort(lst, key=lambda x: x) # probably it can be written in a better way WITHOUT lambda x: x with the help of a standard function 我需要Python 3

Python3中是否有用于函数lambda x:x的内置函数?有时它可能会使一些代码更优雅。例如:

def my_sort(lst, key):
    ...

lst = [4, 3, 7, 1, 9]
my_sort(lst, key=lambda x: x)   # probably it can be written in a better way WITHOUT lambda x: x with the help of a standard function

我需要Python 3中的内置函数或标准函数,而不是像lambda x:x这样的表达式来改进我的代码。

pythonic方法是使用默认参数None,使key可选:

def my_sort(lst, key=None):
    if key is None:
        key = lambda x: x
    ...

lst = [4, 3, 7, 1, 9]
my_sort(lst)

键=无?。。。。为什么连钥匙都有?@COLDSPEED None不是一个函数。你要求的是更优雅的东西。。。你还想要什么?lambda x:x恰好是身份函数,没有人能熟练地模仿它。也许你应该给我们展示一个更好的例子,说明身份函数在哪里真正有用。FWIW,如果lambda x:x执行此任务,则它没有问题,尽管它没有C中编码的函数快,并且您要传递它的函数不接受类似None的特殊值,以指示它应该使用identity函数。我想您可以执行identity=functools.partiallambda x:x:您甚至可以将密钥声明缩短为key=key或lambda x:x。但这不是一些人喜欢的:.def my_sortlst,key=lambda x:x,也是可能的,对吧?谢谢你的回答。但是,请仔细阅读我的问题。@stack\n\u queue None使它看起来更像内置的sorted:sortedeterable,/,*,key=None,reverse=False。