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 ...
随机推荐
- 自定义配置Springboot内嵌的tomcat
两种方法都可以:例子:在tomcat里添加MIME类型,application/wasm 1. import org.springframework.boot.web.embedded.tomcat. ...
- 博弈论练习8 Northcott Game(取石子问题)
题目链接在这里:I-Northcott Game_牛客竞赛博弈专题班组合游戏基本概念.对抗搜索.Bash游戏.Nim游戏习题 (nowcoder.com) 这题是一个伪装的很好的取石子问题,可以发现, ...
- C++ condition_variable
一.使用场景 在主线程中创建一个子线程去计数,计数累计100次后认为成功,并告诉主线程:主线程收到计数100次完成的信息后继续往下执行 二.条件变量的成员函数 wait:当前线程调用 wait() 后 ...
- pandas加速读取数据记录csv大文件处理
def readf(file): t0 = time.time() data=pd.read_csv(file,low_memory=False,encoding='gbk' #,nrows=100 ...
- 爬快手,graphql查询语言
graphql查询语言:https://blog.csdn.net/qq_41882147/article/details/82966783 即:前端调用同一个接口传入不同的操作,得到不同的返回值 一 ...
- c++中文编码格式
c++程序中涉及到中文字符的输入输出以及其他操作经常会出现乱码.乱码主要是由于程序的源文件编码.可执行文件编码以及程序运行环境的编码不匹配导致.比如,c++源程序文件编码为GB18030, 在源程序中 ...
- laravel groupBy 分页
$model=DB::table('tablebname') ->where(function($query) use ($res){ $query->where('xx','xx'); ...
- 如何规避MyBatis使用过程中带来的全表更新风险
作者:京东零售 贾玉西 一.前言 程序员A: MyBatis用过吧? 程序员B: 用过 程序员A: 好巧,我也用过,那你遇到过什么风险没?比如全表数据被更新或者删除了. 程序员B: 咔,还没遇到过,这 ...
- GO语言学习笔记-测试篇 Study for Go ! Chapter ten- Test
持续更新 Go 语言学习进度中 ...... GO语言学习笔记-类型篇 Study for Go! Chapter one - Type - slowlydance2me - 博客园 (cnblogs ...
- C++温故补缺(十九):atomic类
atomic 参考:c++11 多线程(3)atomic 总结 - 简书.c++11 atomic Npgw的博客.C++11 并发指南系列 - Haippy - 博客园. atomic_flag a ...