1 2
| from operator import add from functools import partial, reduce
|
列表解析
1 2
| a_list = [item**2 for item in range(5)] print(a_list)
|
[0, 1, 4, 9, 16]
字典解析
1 2
| a_dict = {"%d^2" % item: item**2 for item in range(5)} print(a_dict)
|
{'3^2': 9, '4^2': 16, '2^2': 4, '1^2': 1, '0^2': 0}
生成器
1
| a_generator = (item**2 for item in range(5))
|
1 2 3
| print(a_generator) print(next(a_generator)) print(next(a_generator))
|
<generator object <genexpr> at 0x103d91200>
0
1
iter
函数和next
函数
1 2 3 4 5
| a_list = ["Jim", "Tom", "Zhang"] a_list_generator = iter(a_list) print(next(a_list_generator)) print(next(a_list_generator)) print(type(a_list), type(a_list_generator))
|
Jim
Tom
<class 'list'> <class 'list_iterator'>
map
函数
1 2 3 4
| print(map(abs, range(-4, 5))) print(list(map(abs, range(-4, 5)))) print(list(map(lambda x: x**2, range(5)))) print(list(map(lambda x, y: x**y, range(1, 5), range(1, 5))))
|
<map object at 0x103f2dbe0>
[4, 3, 2, 1, 0, 1, 2, 3, 4]
[0, 1, 4, 9, 16]
[1, 4, 27, 256]
reduce
函数
1
| print(reduce(lambda x, y: x+y, range(10)))
|
45
1 2 3 4
| def fn(n): return reduce(lambda x, y: x*y,range(1, n+1)) fn(5)
|
120
filter
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import math def isPrime(n): if n > 2: for i in range(2, int(math.sqrt(n)+1)): if n % i == 0: return False elif n ==2: return True else: return False return True list(filter(isPrime, range(100)))
|
[2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97]
any
和all
False
True
enumerate
函数
1 2
| for item, index in enumerate(range(1, 6)): print("%d: %d" % (index, item))
|
1: 0
2: 1
3: 2
4: 3
5: 4
zip
函数
1 2
| for a, b in zip([1, 2, 3], ["a", "b", "c"]): print(a, b)
|
1 a
2 b
3 c
1 2
| a_dict = dict(zip([1, 2, 3], ["a", "b", "c"])) print(a_dict)
|
{1: 'a', 2: 'b', 3: 'c'}
1 2 3 4
| print(int("10010", base=2)) int_base_2 = partial(int, base=2) print(int_base_2("10010")) int_base_2
|
18
18
functools.partial(<class 'int'>, base=2)