python 高级函数补充
补充几个高级函数
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 高级函数补充的更多相关文章
- python 高级函数
高级函数 map 格式:map(func, lt) 说明:接受两个参数,一个函数和一个可迭代对象,返回一个生成器,将func依次作用于lt 示例: l = [1,2,3,4,5]def double ...
- python 之前函数补充(__del__, item系列, __hash__, __eq__) , 以及模块初体验
__str__ : str(obj) , 需求必须实现了 __str__, 要求这个方法的返回值必须是字符串 str 类型 __repr__ (意为原型输出): 是 __str__ 的备胎( ...
- python高级函数
1 函数 1.1 函数即变量 函数定义:把一个函数体作为变量赋值给一个函数名,同时函数体存放到内存中. 函数调用:根据函数名去内存中寻找对用的函数体,找到了就执行. >>> def ...
- Python高级函数--map/reduce
名字开头大写 后面小写:练习: def normalize(name): return name[0].upper() + name[1:].lower() L1 = ['adam', 'LISA', ...
- Python高级函数--filter
def is_palindrome(n): return str(n) == str(n)[::-1] #前两个‘:’表示整个范围,‘-’表示从后面,‘1’表示数据间隔 output = filter ...
- python高级之函数
python高级之函数 本节内容 函数的介绍 函数的创建 函数参数及返回值 LEGB作用域 特殊函数 函数式编程 1.函数的介绍 为什么要有函数?因为在平时写代码时,如果没有函数的话,那么将会出现很多 ...
- 第一篇:python高级之函数
python高级之函数 python高级之函数 本节内容 函数的介绍 函数的创建 函数参数及返回值 LEGB作用域 特殊函数 函数式编程 1.函数的介绍 为什么要有函数?因为在平时写代码时,如果没 ...
- Python函数式编程(一):高级函数
首先有一个高级函数的知识. 一个函数可以接收另一个函数作为参数,这种函数就称之为高阶函数. def add(x, y, f): return f(x) + f(y) 当我们调用add(-, , abs ...
- Day11 Python基础之装饰器(高级函数)(九)
在python中,装饰器.生成器和迭代器是特别重要的高级函数 https://www.cnblogs.com/yuanchenqi/articles/5830025.html 装饰器 1.如果说装 ...
- python高级特性和高阶函数
python高级特性 1.集合的推导式 列表推导式,使用一句表达式构造一个新列表,可包含过滤.转换等操作. 语法:[exp for item in collection if codition] if ...
随机推荐
- python学习记录(五)-文件操作
open()参数说明 ''' 参数1:路径 ./当前目录 ../上一级目录 参数2: 基础模式:w r x a w:写入,不存在则创建,存在则打开,清空文件内容,光标指向最前面 r:只读,不存在则报错 ...
- jenkins脚本
1.统计代码 pipeline { agent any parameters { choice( description: '你需要选择当前哪个分支进行统计 ?', name: 'branchNow' ...
- Executors.newScheduledThreadPool()定时任务线程池
定时任务线程池是由 Timer 进化而来 jdk中的计划任务 Timer 工具类提供了以计时器或计划任务的功能来实现按指定时间或时间间隔执行任务,但由于 Timer 工具类并不是以池 pool ,而是 ...
- 通过cpolar内网穿透 https://blog.csdn.net/CpolarLisa/article/details/128148698
远程办公:通过cpolar内网穿透,远程桌面控制家里公司内网电脑_Cpolar Lisa的博客-CSDN博客 https://blog.csdn.net/CpolarLisa/article/deta ...
- linux使用iperf3测试带宽
1. https://www.alibabacloud.com/help/zh/express-connect/latest/test-the-performance-of-an-express-co ...
- .bat 脚本替换文件内容
rem 定义变量延迟环境,关闭回显 @echo off&setlocal enabledelayedexpansion rem 读取a.txt所有内容 for /f "eol=* t ...
- excel里面嵌入一个表格
excel里怎么嵌入表格 excel是我们工作中经常会用的软件,有时两表格想放在一起比较,但是行高列宽调起来顾此失彼,so: 软件版本:Microsoft Office Excel 2010 操作系统 ...
- 入门IDEA
Hello world psvm sout public class HelloWord { public static void main(String[] args) { System.out.p ...
- web目录扫描工具
在对Web网站进行审计时,首先我们会对进场出现的/admin和robots.txt等信息和目录进行初步的审计获取重要的信息,但是手动猜测目录过于缓慢,使用工具能够迅速的爆破出目录 目录爆破取决于字典的 ...
- 【chatQA】nvm包版本管理
如何使用nvm来管理不同版本的 Node.js,然后使用不同的 Node.js 版本来运行不同版本的 React 应用? 要使用 nvm 来管理不同版本的 Node.js,可以按照以下步骤进行操作: ...