Python 学习笔记(五)杂项
1. Assert
assert len(unique_characters) <= 10, 'Too many letters' #…等价于: if len(unique_characters) > 10:raise AssertionError('Too many letters'
2.找出不同字母
>>> words = ['SEND', 'MORE', 'MONEY'] >>> ''.join(words) #join 字符串连接符 'SENDMOREMONEY' >>> set(''.join(words)) #set 返回不重复字符 {'E', 'D', 'M', 'O', 'N', 'S', 'R', 'Y'}
3. List Set Tuple
>>> unique_characters = {'E', 'D', 'M', 'O', 'N', 'S', 'R', 'Y'} >>> tuple(ord(c) for c in unique_characters) (89, 83, 82, 77, 79, 78, 69, 68) >>> set(ord(c) for c in unique_characters) {68, 69, 77, 78, 79, 82, 83, 89} >>> list(ord(c) for c in unique_characters) [89, 83, 82, 77, 79, 78, 69, 68]
4. 排列
list(itertools.permutations('ABC', 3)) #取ABC 3个元素的排列组合 [('A', 'B', 'C'), ('A', 'C', 'B'),('B', 'A', 'C'), ('B', 'C', 'A'),('C', 'A', 'B'), ('C', 'B', 'A')]
5. 排列分组
>>> names = ['Alex', 'Anne', 'Chris', 'Dora', 'Ethan','John', 'Lizzie', 'Mike', 'Sarah', 'Wesley']
>>> import itertools
>>> groups = itertools.groupby(names,len)
>>> groups
<itertools.groupby object at 0x01433F30>
>>> list(groups)
[(4, <itertools._grouper object at 0x013DA830>),(5, <itertools._grouper object at 0x01426190>),(4, <itertools._grouper object at 0x01426C70>),(5, <itertools._grouper object at 0x01426130>),(4, <itertools._grouper object at 0x01426030>),(6, <itertools._grouper object at 0x014261D0>),(4, <itertools._grouper object at 0x014265D0>),(5, <itertools._grouper object at 0x01426110>),(6, <itertools._grouper object at 0x01426150>)]
>>> names = sorted(names,key=len) #列表需要排序才能group by
>>> names
['Alex','Anne','Dora','John','Mike','Chris','Ethan','Sarah','Lizzie','Wesley']
>>> A = itertools.groupby(names,len)
>>> list(A) #调用list()
函数会“耗尽”这个迭代器, 也就是说 你生成了迭代器中所有元素才创造了这个列表
[(4, <itertools._grouper object at 0x014261D0>),(5, <itertools._grouper object at 0x014268D0>),(6, <itertools._grouper object at 0x01426C90>)]
>>> for name_len, name_iter in A: #List(A) 为空
... print('%d' %(name_len))
... for name in name_iter:
... print(name)
...
>>>
>>> A = itertools.groupby(names,len) #重新产生
>>> for name_len, name_iter in A:
... print('%d' %(name_len))
... for name in name_iter:
... print(name)
...
4
Alex
Anne
Dora
John
Mike
5
Chris
Ethan
Sarah
6
Lizzie
Wesley
6. List 的extend 和append的差别
>>> a_list = ['a','b','c'] >>> a_list.extend(['d','e']) #extend() 方法只接受一个参数,而该参数总是一个列表 >>> a_list ['a', 'b', 'c', 'd', 'e'] >>> len(a_list) 5 >>> a_list.append(['f','g']) #append() 方法只接受一个参数,但可以是任何数据类型 >>> a_list ['a', 'b', 'c', 'd', 'e', ['f', 'g']] >>> len(a_list) 6
7. Set 的discard和remove的差别
>>> a_set = {1, 3, 6, 10, 15, 21, 28, 36, 45} >>> a_set {1, 3, 36, 6, 10, 45, 15, 21, 28} >>> a_set.discard(10) ① >>> a_set {1, 3, 36, 6, 45, 15, 21, 28} >>> a_set.discard(10) ② >>> a_set {1, 3, 36, 6, 45, 15, 21, 28} >>> a_set.remove(21) ③ >>> a_set {1, 3, 36, 6, 45, 15, 28} >>> a_set.remove(21) ④ Traceback (most recent call last):File "<stdin>", line 1, in <module> KeyError: 21 #区别在于:如果该值不在集合中,remove() 方法引发一个 KeyError 例外
8.混合字典
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']} >>> SUFFIXES[1024] ④ ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] >>> SUFFIXES[1000][3] ⑤ # 'TB'
9.文件路径操作
>>> import os >>> print(os.getcwd()) #当前工作路径 D:\study\workspace\pythonTest\src >>> print(os.path.expanduser('~')) #$home路径 C:\Documents and Settings\yfzhou >>> print(os.path.join(os.path.expanduser('~'),'hello','world','python.py')) #构建动态的文件夹和文件 ... C:\Documents and Settings\yfzhou\hello\world\python.py
10. 罗列目录下的文件
>>> os.chdir('/Users/pilgrim/diveintopython3/') #改变当前路径 >>> import glob >>> glob.glob('examples/*.xml') #返回匹配的文件 ['examples\\feed-broken.xml', 'examples\\feed-ns0.xml', 'examples\\feed.xml'] >>> os.chdir('examples/') #改变路径 >>> glob.glob('*test*.py') #返回匹配的通配符文件 ['alphameticstest.py', 'pluraltest1.py' ]
11.文件元信息
>>> metadata = os.stat('roman.py') #用os.stat() 函数返回一个包含多种文件元信息的对象 >>> metadata.st_mtime 1373272096.4869184 >>> import time >>> time.localtime(metadata.st_mtime) time.struct_time(tm_year=2013, tm_mon=7, tm_mday=8, tm_hour=16, tm_min=28, tm_sec=16, tm_wday=0, tm_yday=189, tm_isdst=0) #可读性更强 >>> metadata.st_size #文件大小 2546 >>> print(os.path.realpath('roman.py')) #文件绝对路径 D:\study\workspace\pythonTest\src\roman.py
12.字典键值互换
>>> a_dict = {'a': 1, 'b': 2, 'c': 3} >>> {value:key for key, value in a_dict.items()} {1: 'a', 2: 'b', 3: 'c'}
13. __str__ and __repr__
- __str__ is tried first for the print operation and the str built-in function (the internal
equivalent of which print runs). It generally should return a user-friendly
display.
- __repr__ is used in all other contexts: for interactive echoes, the repr function, and
nested appearances, as well as by print and str if no __str__ is present. It should
generally return an as-code string that could be used to re-create the object, or a
detailed display for developers
>>> class addboth(adder): ... def __str__(self): ... return '[Value: %s]' % self.data # User-friendly string ... def __repr__(self): ... return 'addboth(%s)' % self.data # As-code string ... >>> x = addboth(4) >>> x + 1 >>> x # Runs __repr__ addboth(5) >>> print(x) # Runs __str__ [Value: 5] >>> str(x), repr(x) ('[Value: 5]', 'addboth(5)')
Two usage notes:
1.keep in mind that __str__ and__repr__ must both return strings
2.depending on a container’s string-conversion logic, the user-friendly display of __str__ might only applywhen objects appear at the top level of a print operation; objects nested in larger objects might still print with their __repr__ or its default
>>> class Printer: ... def __init__(self, val): ... self.val = val ... def __str__(self): # Used for instance itself ... return str(self.val) # Convert to a string result ... >>> objs = [Printer(2), Printer(3)] >>> for x in objs: print(x) # __str__ run when instance printed ... # But not when instance in a list! 2 3 >>> print(objs) [<__main__.Printer object at 0x025D06F0>, <__main__.Printer object at ...more... >>> objs [<__main__.Printer object at 0x025D06F0>, <__main__.Printer object at ...more...---------------------------- >>> class Printer: ... def __init__(self, val): ... self.val = val ... def __repr__(self): # __repr__ used by print if no __str__ ... return str(self.val) # __repr__ used if echoed or nested ... >>> objs = [Printer(2), Printer(3)] >>> for x in objs: print(x) # No __str__: runs __repr__ ... 23 >>> print(objs) # Runs __repr__, not ___str__ [2, 3] >>> objs [2, 3]
转载于:https://www.cnblogs.com/zyf7630/p/3165292.html
Python 学习笔记(五)杂项相关推荐
- Python学习笔记五:控制语句
Python学习笔记五:控制语句 Pycharm 开发环境的下载安装配置_项目管理 控制语句 Pycharm 开发环境的使用 Pycharm 下载和安装 激活和选择不同UI 风格 创建项目和初始化配置 ...
- Python学习笔记(五)—LOOP 循环
个人认为Python基础学习直到LOOP才算真正开始. 循环有While, do-while, 和for() 比如while 我们要输出100条"you are my sunshine &q ...
- 【懒懒的Python学习笔记五】
在这一章中,你将学习到能够将信息关联起来的Python字典,将学习如何访问和修改字典中的信息,同时也会学习如何遍历字典中的数据. 一.一个简单的字典 新建了一个存储用户信息的字典,里面存储了用户姓名. ...
- Python学习笔记五:条件循环
文章目录 一.再谈print和import 1. 打印多个参数 2. 导入时重命名 二.赋值魔法 1. 序列解包 2. 链式赋值 3. 增强赋值 三.代码块:缩进的乐趣 四.条件和条件语句 1. 这正 ...
- Python学习笔记五--条件和循环
5.1 if语句 没什么好说,if语句语法如下: if expression: expr_true_suit 5.1.1多重条件表达式 单个if语句可以通过布尔操作符and,or,not实现多重条件判 ...
- python函数是一段具有特定功能的语句组_Python学习笔记(五)函数和代码复用
本文将为您描述Python学习笔记(五)函数和代码复用,具体完成步骤: 函数能提高应用的模块性,和代码的重复利用率.在很多高级语言中,都可以使用函数实现多种功能.在之前的学习中,相信你已经知道Pyth ...
- Python学习笔记总结
了解了python语言后,决定以后使用python来进行各项工作,因此一直想要深入学习python.千里之行始于足下,万事开头难. 由于最近在准备写毕业论文,陆陆续续学习了Python的语法知识. P ...
- python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹
python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...
- python学习笔记(五)缩进
python学习笔记(五)缩进 原作:http://www.cnblogs.com/vamei/archive/2012/05/29/2524706.html 笔记: #!/usr/bin/env p ...
- 5岁自学python编程-python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹...
python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...
最新文章
- 今日工作总结及计划: 2022-02-14
- Linux/Centos服务器安装portsentry防恶意端口扫描
- 创建一个存储过程,返回指定员工的姓名和薪水
- aspcms各版本漏洞0day集合
- C语言 | 直接插入排序
- Mybatis-plus批量插入、批量修改数据saveBatch等速度缓慢
- jadc连接oracle,用jdbc连接oracle的第一次经历
- C语言 关键字 | typedef
- 各省简称 拼音 缩写_中国各省、直辖市、自治区名称汉语拼音字母缩
- 考研逻辑整理 - 概念和概念的种类
- 在线ER模型设计工具,支持MySQL、SQLServer、Oracle、Postgresql sql导入,支持表、视图等编辑
- google 安装去广告插件
- 跟着小马哥学系列之 Spring AOP(Pointcut 组件详解)
- 什么是ASP .NET?
- linux shell 10进制转16进制
- app常见的专项测试以及面试题
- 联想think station D30安装系统的时候找不到硬盘的解决方法
- js 字符串转化成数字
- swift 设置 pickerView 为黑底白字
- 概率初步(1 Juin, 2019)
热门文章
- Codeforces 948D Perfect Security
- Oracle之:查询锁表,删除锁表
- 配置管理系统和整体的变化对系统有什么区别和联系
- 【Andorid学习】declare-styleable:自定义控件的属性
- bnx2: Can't load firmware file bnx2/bnx2-mips-09-6.2.1b.fw
- linux shell if命令参数说明
- linux sar 历史负载,sar 查看历史负载
- 大数据技术的特点有哪些
- 语言 全排列 函数_【排列组合】错位全排列的简化计算公式
- mulitpartfile怎么接收不到值_GNSS接收机设计杂谈(射频前端+捕获)