码迷,mamicode.com
首页 > 编程语言 > 详细

Python-功能函数的使用(二)

时间:2017-01-19 18:15:55      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:内联   语句   round   分配   包含   bsp   strip   list sort   nal   

使用可选参数定义函数

可选参数可以通过分配(用定义=)的默认值的参数名:

def make(action=nothing):
    return action

可以通过3种不同的方式调用此函数:

make("fun")
# Out: fun

make(action="sleep")
# Out: sleep

# The argument is optional so the function will use the default value if the argument is 
# not passed in.
make()   
# Out: nothing

警告

可变类型(listdictset等),应小心时,给出被视为默认属性。默认参数的任何突变将永久更改。

 

Lambda(内联/匿名)函数

lambda关键字创建一个包含一个表达式的内联函数。

考虑功能:

def greeting():
    return "Hello"

其中,当称为:

print(greeting())

打印:

Hello

lambda s也可以接受参数:

strip_and_upper_case = lambda s: s.strip().upper()

strip_and_upper_case("  Hello   ")

返回字符串:

HELLO

他们甚至可以采取任意数量的参数/关键字参数,如正常功能。

greeting = lambda x, *args, **kwargs: print(x, args, kwargs)
greeting(‘hello‘, ‘world‘, world=‘world‘)

打印:

hello (world,) {world: world}

最常见的用例lambdas为那些只在一个地方使用简短的函数。例如,此行排列一个字符串列表,忽略它们的大小写,并在开头和结尾忽略空格:

它们最常用于sortedfiltermap

 

sorted( [" foo ", "    BAR", "BaZ    ", "qux"], key=lambda s: s.strip().upper())

 

返回:

[    BAR, BaZ    ,  foo , qux]

==================================================== =========


sorted([" foo ", "    BAR", "BaZ    ", "qux"], key=lambda s: s.strip())

返回:

[    BAR, BaZ    ,  foo , qux] # no effect of lambda, list is sorted

sorted([" foo ", "    BAR", "BaZ    ", "qux"])

返回:

[    BAR, BaZ    ,  foo , qux] # list sorted.

sorted( map(lambda s: s.strip().upper(), [" foo ", "    BAR", "BaZ    ", "qux"]))

返回:

[BAR, BAZ, FOO, QUX] # what expected

是第一个成语错了吗?你能解释一下这个。

==================================================== =====================


my_list = [3, -4, -2, 5, 1, 7]
sorted(my_list, key=lambda x: abs(x))

返回:

[1, -2, 3, -4, 5, 7]

list(filter(lambda x: x>0, my_list)

返回:

[3, 5, 1, 7]

list(map(lambda x: abs(x), my_list)

返回:

[3, 4, 2, 5, 1, 7]

可以从lambda函数内部调用其他函数(带/不带参数)。

def foo(msg):
    print(msg)

greet = lambda x = "hello world": foo(x)
greet()

打印:

hello world

因为这是非常有用的lambda可以仅含有一个表达,并通过使用一个附属功能的一个可以运行多个语句。


 

注意

记住,PEP-8 官方Python风格指南)不建议lambda表达式分配给变量(如在第一两个例子):

始终使用def语句,而不是将lambda表达式直接绑定到标识符的赋值语句。

是:

def f(x): return 2*x

没有:

f = lambda x: 2*x

第一种形式是指所得到的函数的对象的名称是特别f,而不是通用的<lambda>这对于一般的跟踪和字符串表示更有用。使用赋值语句消除的唯一好处在一个lambda表达式可以提供一个明确的def声明(即它可以嵌入一个更大的表达式中)。

Python-功能函数的使用(二)

标签:内联   语句   round   分配   包含   bsp   strip   list sort   nal   

原文地址:http://www.cnblogs.com/jintk/p/6307523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!