自定义一个函数:
>>> def hi(name=''):
... print 'hello, {}'.format(name)
... return None
...
>>> hi()
hello,
>>> hi('everyone')
hello, everyone
匿名函数和map用法:
>>> func = lambda x : x ** 2
>>> func(20)
400
>>> a_list = range(10)
>>> a_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> map(func, a_list)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> map(lambda x : x ** 2, a_list)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
列表、字典推导式:
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> a_list = range(10)
>>> a_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b_list = [i * i for i in a_list]
>>> b_list
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> b_dict = {i: string.letters[i] for i in a_list}
>>> print b_dict
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j'}
列表 、字典 解析式