高级函数

1. zip
将两个可迭代内容合成一个tuple类型元素组成的可迭代内容

l1 = ["a", "b", "c", "d", "e"]
l2 = [1, 2, 3, 4, 5]
z = zip(l1, l2)
for i in z:
		print(i)

结果如下:

('a', 1)
('b', 2)
('c', 3)
('d', 4)
('e', 5)

2. enumerate 枚举
将列表元素加上索引,生成tuple类型元素组成的可迭代内容

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)]
  • 修改索引的起始点
l1 = [11, 22, 33, 44, 55]
em = enumerate(l1, start = 100)
l2 = [i for i in em]
print(l2)

结果如下:

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

3. namedtuple

  • 生成可以使用名字来访问元素内容的tuple子类
  • 需要加载collections模块
import collections
Point = collections.namedtuple("Point", ["x", "y"])
p = Point(11, 22)
print(p)
print(p.x)
print(p[1])

结果

Point(x=11, y=22)
11
22
Circle = collections.namedtuple("Circle", ["x", "y", "r"])
c = Circle(100, 150, 50)
print(c)
print(isinstance(c, tuple))

结果为

Circle(x=100, y=150, r=50)
True

4. deque

  • 比较方便的解决了频繁删除插入带来的效率问题
  • 需要加载collections模块
from collections import deque
q = deque(["a", "b", "c", "d"])
q.append("e")
print(q)
q.appendleft("x")
print(q)

结果如下

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

5. defaultdict

  • 当直接读取dict不存在的属性时,直接返回默认值
  • 需要加载collections模块
  • defaultdict(function)
from collections import defaultdict
func = lambda: "没有找到"
d2 = defaultdict(func)
d2["one"] = 1
d2["two"] = 2
print(d2["two"])
print(d2["six"])
  • Counter
  • 统计字符串个数
  • 需要加载collections模块
from collections import Counter
c1 = Counter("abdcadcdabcccabc")
print(c1)
c2 = Counter(["Beijing", "Tianjin", "Shenzhen", "Beijing"])
print(c2)

结果如下

Counter({'c': 6, 'a': 4, 'b': 3, 'd': 3})
Counter({'Beijing': 2, 'Tianjin': 1, 'Shenzhen': 1})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值