补充几个高级函数

zip

  • 把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容
# 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) help(zip)
<class 'zip'>
<zip object at 0x054A1BE8>
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)
Help on class zip in module builtins: class zip(object)
| zip(iter1 [,iter2 [...]]) --> zip object
|
| Return a zip object whose .__next__() method returns a tuple where
| the i-th element comes from the i-th iterable argument. The .__next__()
| method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises StopIteration.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
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类型
# 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)]
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
import collections
Point = collections.namedtuple("Point", ['x', 'y'])
p = Point(11, 22)
print(p.x)
print(p[0])
11
11
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'> True

dequeue

  • 比较方便的解决了频繁删除插入带来的效率问题
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不存在的属性时,直接返回默认值
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'
from collections import defaultdict
# lambda表达式,直接返回字符串
func = lambda: "saedade"
d2 = defaultdict(func) d2["one"] = 1
d2["two"] = 2 print(d2['one'])
print(d2['four'])
1
saedade

Counter

  • 统计字符串个数
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})
s = ["sadfa", "love", "love", "love", "love", "asdfaed"]
c = Counter(s) print(c)
Counter({'love': 4, 'sadfa': 1, 'asdfaed': 1})

python 高级函数补充的更多相关文章

  1. python 高级函数

    高级函数 map 格式:map(func, lt) 说明:接受两个参数,一个函数和一个可迭代对象,返回一个生成器,将func依次作用于lt 示例: l = [1,2,3,4,5]​def double ...

  2. python 之前函数补充(__del__, item系列, __hash__, __eq__) , 以及模块初体验

    __str__ :  str(obj) ,  需求必须实现了 __str__, 要求这个方法的返回值必须是字符串  str  类型 __repr__ (意为原型输出):  是 __str__ 的备胎( ...

  3. python高级函数

    1 函数 1.1 函数即变量 函数定义:把一个函数体作为变量赋值给一个函数名,同时函数体存放到内存中. 函数调用:根据函数名去内存中寻找对用的函数体,找到了就执行. >>> def ...

  4. Python高级函数--map/reduce

    名字开头大写 后面小写:练习: def normalize(name): return name[0].upper() + name[1:].lower() L1 = ['adam', 'LISA', ...

  5. Python高级函数--filter

    def is_palindrome(n): return str(n) == str(n)[::-1] #前两个‘:’表示整个范围,‘-’表示从后面,‘1’表示数据间隔 output = filter ...

  6. python高级之函数

    python高级之函数 本节内容 函数的介绍 函数的创建 函数参数及返回值 LEGB作用域 特殊函数 函数式编程 1.函数的介绍 为什么要有函数?因为在平时写代码时,如果没有函数的话,那么将会出现很多 ...

  7. 第一篇:python高级之函数

    python高级之函数   python高级之函数 本节内容 函数的介绍 函数的创建 函数参数及返回值 LEGB作用域 特殊函数 函数式编程 1.函数的介绍 为什么要有函数?因为在平时写代码时,如果没 ...

  8. Python函数式编程(一):高级函数

    首先有一个高级函数的知识. 一个函数可以接收另一个函数作为参数,这种函数就称之为高阶函数. def add(x, y, f): return f(x) + f(y) 当我们调用add(-, , abs ...

  9. Day11 Python基础之装饰器(高级函数)(九)

    在python中,装饰器.生成器和迭代器是特别重要的高级函数   https://www.cnblogs.com/yuanchenqi/articles/5830025.html 装饰器 1.如果说装 ...

  10. python高级特性和高阶函数

    python高级特性 1.集合的推导式 列表推导式,使用一句表达式构造一个新列表,可包含过滤.转换等操作. 语法:[exp for item in collection if codition] if ...

随机推荐

  1. GoAccess - 可视化 Web 日志分析工具

    Centos安装: yum -y install goaccess 使用goaccess命令生成HTML文件 LANG="en_US.UTF-8" bash -c 'goacces ...

  2. Field userService in com.lin.hms.controller.LogController required a bean of type 'org.lin.hms.service.UserService' that could not be found.

    需要一个bean但找不到 解决 我们在controller使用的service没有注入spring容器,那么我们可以在启动类上,加上包扫描注解,让这个bean所在的包能扫描到: @ComponentS ...

  3. 上位机-串口通信详解(以RS232为例))

    1.什么是串口通信? 写这个的时候我在想应该怎么解释串口通信,因为串口通信很多朋友不了解的原因是涉及到硬件的知识,对于没有相关专业知识的朋友很难理解串口通信.所以我这里只做部分的解释,需要了解更多硬件 ...

  4. vue3 ThreeJS 引入obj模型过暗的问题

    当我单纯地用MTLLoader引入材质, OBJLoader引入模型并添加到场景中时, 发现模型非常得暗. 需要将环境光的强度设置到3.5左右看起来才比较正常. 但正常情况下环境光的值不应该超出1.  ...

  5. rosetta Resfile语法和约束

    介绍 参考:https://www.rosettacommons.org/docs/latest/rosetta_basics/file_types/resfiles resfile包含输入到Pack ...

  6. FastJson参数

    名称 含义 备注 QuoteFieldNames 输出key时是否使用双引号,默认为true   UseSingleQuotes 使用单引号而不是双引号,默认为false   WriteMapNull ...

  7. 个人数据保全计划:(2) NAS基础知识

    前言 距离去年国庆入手了NAS至今有好几个月时间了,NAS折腾起来有点麻烦,且实际作用因人而异,并没有想象中的好用,所以说好的这个系列一直没有更新~ 还有另一方面的原因,这些NAS的系统基于Linux ...

  8. Python ArcPy批量拼接长时间序列栅格图像

      本文介绍基于Python中ArcPy模块,对大量不同时相的栅格遥感影像按照其成像时间依次执行批量拼接的方法.   在前期的文章Python arcpy创建栅格.批量拼接栅格中,我们介绍了利用Pyt ...

  9. 声网 Agora 音频互动 MoS 分方法:为音频互动体验进行实时打分

    在业界,实时音视频的 QoE(Quality of Experience) 方法一直都是个重要的话题,每年 RTE 实时互联网大会都会有议题涉及.之所以这么重要,其实是因为目前 RTE 行业中还没有一 ...

  10. python基础篇:Python基础知识,帮助初学者快速入门

    Python是一种高级编程语言,它易于学习和使用,因此成为了许多人的首选编程语言.本文将介绍Python的基础知识,以帮助初学者快速入门. 安装Python 在开始学习Python之前,您需要安装Py ...