自定義一個(gè)函數(shù):
>>> def hi(name=''):
... print 'hello, {}'.format(name)
... return None
...
>>> hi()
hello,
>>> hi('everyone')
hello, everyone
匿名函數(shù)和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]
列表壁拉、字典推導(dǎo)式:
>>> 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'}
列表 谬俄、字典 解析式