1、高级函数
函数本身也可以赋值给变量,即:变量可以指向函数;
如果一个变量指向了一个函数,可通过该变量来调用这个函:
>>> f = abs
>>> f(-10)
10
直接调用abs()
函数和调用变量f()
完全相同。
2、map\reduce
map()
函数接收两个参数,一个是函数,一个是Iterable
,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator
返回
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return digits[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579
3、filter
filter()
函数用于过滤序列。
filter()
接收一个函数和一个序列,filter()
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素。
在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']
上面代码中如果将代码改为return s.strip()或s.strip() and s,报错:AttributeError: 'NoneType' object has no attribute 'strip'
nonetype类型的变量无法调用strip(), 所以 s and s.strip() 先判断了s的值再执行strip()
(附集合中空字符串和none删除方法)
time_list = ['', '', ' ', None, 1,2,3]
print time_list
['', '', ' ', None, 1, 2, 3]
ret = [str for str in time_list if str not in ['', ' ', None]]
print ret
[1, 2, 3]
4、sorted
实现对list的排序,默认排序:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
sorted()
函数也是一个高阶函数,它还可以接收一个key
函数来实现自定义的排序,例如按绝对值大小排序:
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
字符串排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']
默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a'
,结果,大写字母Z
会排在小写字母a
的前面,忽略大小写排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True
:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
and和or的运行机制
一、and:
>>> 'a' and 'b'
'b'
>>> ' ' and 'b'
' '
>>> 'a' and 'b' and 'c'
'c'
在布尔上下文中从左到右演算表达式的值,如果布尔上下文中的所有值都为真,那么 and 返回最后一个值。
如果布尔上下文中的某个值为假,则 and 返回第一个假值
二、or:
>>> 'a' or 'b'
'a'
>>> ' ' or 'b'
'b'
>>> ' ' or [ ] or { }
{}
>>> 0 or 'a' or 'c'
'a'
使用 or 时,在布尔上下文中从左到右演算值,就像 and 一样。如果有一个值为真,or 立刻返回该值
如果所有的值都为假,or 返回最后一个假值
注意 :or 在布尔上下文中会一直进行表达式演算直到找到第一个真值,然后就会忽略剩余的比较值
三、and-or:
and-or 结合了前面的两种语法
>>> a = 'first'
>>> b = 'second'
>>> 1 and a or b
'first'
>>> (1 and a) or b
'first'
>>> 0 and a or b
'second'
>>> (0 and a) or b
'second'
整个表达式从左到右进行演算,所以先进行 and 表达式的演算。 1 and 'first' 演算值为 'first',然后 'first' or 'second' 的演算值为 'first'。
0 and 'first' 演算值为 False,然后 0 or 'second' 演算值为 'second'。
四、安全使用and-or
>>> a = ' '
>>> b = 'second'
>>> (1 and [a] or [b])
[' ']
>>> (1 and [a] or [b])[0]
''
由于 [a] 是一个非空列表,所以它决不会为假。即使 a 是 0 或者 '' 或者其它假值,列表 [a] 也为真,因为它有一个元素。
将 and-or 技巧封装成一个函数:
def choose(bool,a,b):
return(bool and [a] or [b])[0]
print choose(1,' ','second')