高级函数
zip
- 把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容
L1 = [1, 2, 3, 4, 5]
L2 = [11, 22, 33, 44, 55]
L3 = zip(L1, L2)
print(type(L3))
print(L3)
#for i in L3:
# print(i)
L4 = [i for i in L3]
print(L4)
<class 'zip'>
<zip object at 0x108070e88>
[(1, 11), (2, 22), (3, 33), (4, 44), (5, 55)]
enumerate
- 和zip功能比较像
- 对可迭代对象里的每一元素,配饰一个索引,然后索引和内容构成tuple类型
L1 = ['a', 'b', 'c']
em = enumerate(L1)
L2 = [i for i in em]
print(L2)
[(0, 'a'), (1, 'b'), (2, 'c')]
em = enumerate(L1, start=100)
L2 = [i for i in em]
print(L2)
[(100, 'a'), (101, 'b'), (102, 'c')]
collections模块
namedtuple
import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(11, 22)
print(p.x)
print(p[0])
#help(collections.namedtuple)
11
11
Circle = collections.namedtuple("Circle", ['x', 'y', 'r'])
c = Circle(100, 150, 50)
print(c)
print(type(c))
isinstance(c, tuple)
Circle(x=100, y=150, r=50)
<class '__main__.Circle'>
True
deque
q = collections.deque(['a', 'b', 'c'])
print(q)
q.append('d')
print(q)
q.appendleft('e')
print(q)
deque(['a', 'b', 'c'])
deque(['a', 'b', 'c', 'd'])
deque(['e', 'a', 'b', 'c', 'd'])
defaultdict
d = {"one":1, "two":2}
print(d["one"])
print(d["four"])
1
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-29-39ba53d60c71> in <module>
2 print(d["one"])
3
----> 4 print(d["four"])
KeyError: 'four'
from collections import defaultdict
func = lambda: "test"
d2 = defaultdict(func)
d2["one"] = 1
d2["two"] = 2
print(d2["four"])
test
Counter
from collections import Counter
c = Counter("dsfajcsdancosad;cadfsiacnsafq")
print(c)
Counter({'a': 6, 's': 5, 'd': 4, 'c': 4, 'f': 3, 'n': 2, 'j': 1, 'o': 1, ';': 1, 'i': 1, 'q': 1})
调试
pdb调试
pycharm调试
单元测试