Python 中的 map lambda
看《Python标准库》,1.8 re 模块。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34# File: re-example-6.py
import re, string
def combined_pattern(patterns):
p = re.compile(
string.join(map(lambda x: "("+x+")", patterns), "|")
)
def fixup(v, m=p.match, r=range(0, len(patterns))):
try:
regs = m(v).regs
except AttributeError:
return None # no match, so m.regs will fail
else:
for i in r:
if regs[i+1] != (-1, -1):
return i
return fixup
patterns = [
r"\d+",
r"abc\d{2,4}",
r"p\w+"
]
p = combined_pattern(patterns)
print p("129391")
print p("abc800")
print p("abc1600")
print p("python")
print p("perl")
print p("tcl")
其中,第 5 行使用了 map 函数和 lambda 表达式。
map 函数
map(function, iterable, …)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
Lambda 表达式
lambda 表达式是一个匿名函数。
Lambda expressions (sometimes called lambda forms) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with
1
2 def name(arguments):
return expression
自己翻译的:
Lambda 表达式在语法同表达式的地位相同。它是创建一个匿名函数的简写法;表达式 lambda arguments: expression 生成一个函数类。这个未命名的类就像下面这个函数类:1
2def name(arguments):
return expression