打赏

6-python基础-函数式编程-高阶函数补充

 

给大家补充几个高级函数

zip

  • 把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容
In [3]:
# zip 案例
l1 = [ 1,2,3,4,5]
l2 = [11,22,33,44,55]

z = zip(l1, l2)

print(type(z))
print(z)

for i in z:
    print(i)

 

 
<class 'zip'>
<zip object at 0x7f61c457ab88>
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)
In [6]:
l1 = ["wangwang", "mingyue", "yyt"]
l2 = [89, 23, 78]

z = zip(l1, l2)

for i in z:
    print(i)
    
    
# 考虑下面结果,为什么会为空
l3 = [i for i in z]
print(l3)

 

 
('wangwang', 89)
('mingyue', 23)
('yyt', 78)
[]
 

enumerate

  • 跟zip功能比较像
  • 对可迭代对象里的每一元素,配上一个索引,然后索引和内容构成tuple类型
In [8]:
# enumerate案例1
l1 = [11,22,33,44,55]

em = enumerate(l1)

l2 = [i for i in em]
print(l2)

 

 
[(0, 11), (1, 22), (2, 33), (3, 44), (4, 55)]
In [9]:
em = enumerate(l1, start=100)

l2 = [ i for i in em]
print(l2)
 

 

[(100, 11), (101, 22), (102, 33), (103, 44), (104, 55)]
 

collections模块

  • namedtuple
  • deque
 

namedtuple

  • tuple类型
  • 是一个可命名的tuple
In [13]:
import collections
Point = collections.namedtuple("Point", ['x', 'y'])
p = Point(11, 22) 
print(p.x)
print(p[0])

 

 
11
11
In [16]:
Circle = collections.namedtuple("Circle", ['x', 'y', 'r'])

c = Circle(100, 150, 50)
print(c)
print(type(c))

# 想检测以下namedtuple到底属于谁的子类
isinstance(c, tuple)

 

 
Circle(x=100, y=150, r=50)
<class '__main__.Circle'>
Out[16]:
True
 

dequeue

  • 比较方便的解决了频繁删除插入带来的效率问题
In [22]:
from collections import deque

q = deque(['a', 'b', 'c'])
print(q)

q.append("d")
print(q)

q.appendleft('x')
print(q)

 

 
deque(['a', 'b', 'c'])
deque(['a', 'b', 'c', 'd'])
deque(['x', 'a', 'b', 'c', 'd'])
 

defaultdict

  • 当直接读取dict不存在的属性时,直接返回默认值
In [27]:
d1 = {"one":1, "two":2, "three":3}
print(d1['one'])
print(d1['four'])

 

 
1
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-27-d54a61646604> in <module>()
      1 d1 = {"one":1, "two":2, "three":3}
      2 print(d1['one'])
----> 3 print(d1['four'])

KeyError: 'four'
In [34]:
from collections import defaultdict
# lambda表达式,直接返回字符串
func = lambda: "刘大拿"
d2 = defaultdict(func)

d2["one"] = 1
d2["two"] = 2

print(d2['one'])
print(d2['four'])

 

 
1
刘大拿
 

Counter

  • 统计字符串个数
In [39]:
from collections import Counter

# 为什么下面结果不把abcdefgabced.....作为键值,而是以其中每一个字母作为键值
# 需要括号里内容为可迭代
c = Counter("abcdefgabcdeabcdabcaba")
print(c)

 

 
Counter({'a': 6, 'b': 5, 'c': 4, 'd': 3, 'e': 2, 'f': 1, 'g': 1})
In [40]:
s = ["liudana", "love", "love", "love", "love", "wangxiaona"]
c = Counter(s)

print(c)

 

 
Counter({'love': 4, 'liudana': 1, 'wangxiaona': 1})

posted on 2018-11-07 19:14  XuCodeX  阅读(78)  评论(0编辑  收藏  举报

导航