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]
Python 学习笔记(五)杂项的更多相关文章
- python学习笔记五 模块上(基础篇)
模块学习 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要 ...
- Python学习笔记五
一. 递归 递归函数: def a (): print ("from b") b() def b(): print("from a ") a() a() 递推和 ...
- Python学习笔记五:错误与异常
一:常见异常与错误 BaseException 所有异常的基类SystemExit 解释器请求退出KeyboardInterrupt 用户中断执行(通常是输入^C)Exception 常规错误的基类S ...
- python学习笔记(五):装饰器、生成器、内置函数、json
一.装饰器 装饰器,这个器就是函数的意思,连起来,就是装饰函数,装饰器本身也是一个函数,它的作用是用来给其他函数添加新功能,比如说,我以前写了很多代码,系统已经上线了,但是性能比较不好,现在想把程序里 ...
- Python学习笔记五(读取提取写入文件)
#Python打开读取一个文件内容,然后写入一个新的文件中,并对某些字段进行提取,写入新的字段的脚本,与大家共同学习. import os import re def get_filelist(dir ...
- Python学习笔记(五)函数和代码复用
函数能提高应用的模块性,和代码的重复利用率.在很多高级语言中,都可以使用函数实现多种功能.在之前的学习中,相信你已经知道Python提供了许多内建函数,比如print().同样,你也可以自己创建函数, ...
- python学习笔记五 模块下(基础篇)
shevle 模块 扩展pickle模块... 1.潜在的陷进 >>> import shelve>>> s = shelve.open("nb" ...
- python学习笔记五--文件
任何情况下文本文件在Python里均是字符串模式. 一.创建一个文件,并写入: 函数open(文件名,w) 二.打开一个文件,并读取: 函数open(文件名,r),“r”是默认值,可以不用写 三.使用 ...
- Python学习笔记五--条件和循环
5.1 if语句 没什么好说,if语句语法如下: if expression: expr_true_suit 5.1.1多重条件表达式 单个if语句可以通过布尔操作符and,or,not实现多重条件判 ...
- Python学习笔记五,函数及其参数
在Python中如何自定义函数:其格式为 def 函数名(函数参数): 内容
随机推荐
- 总结JavaScript(Iframe、window.open、window.showModalDialog)父窗口与子窗口之间的操作
一.Iframe 篇 //&&&&&&&&&&&&&&&&&&a ...
- c# 获取字符串数组中最长的的字符串并输出最长的字符串
求字符串数组中最大长度的字符串: 实质就是比较字符串的长度: 方案一: class Program { static void Main(string[] args) { string[] array ...
- 《Linux/Unix系统编程手册》读书笔记 目录
<Linux/Unix系统编程手册>读书笔记1 (创建于4月3日,最后更新4月7日) <Linux/Unix系统编程手册>读书笔记2 (创建于4月9日,最后更新4月10日) ...
- AE 栅格处理
由RasterDataset得到RasterLayer RasterDataset->RasterLayer IRasterLayer pRasterLayer = new RasterLaye ...
- Js判断一个单词是否有重复字母
今天上午刷到一道题,大体是写一个方法判断一个单词中是否有重复的字母(或者说一个字符串中是否有重复的字符).我的思路是一个字符一个字符地遍历,如果发现有重复的停止: function isIsogram ...
- Newtonsoft.Json高级用法 1.忽略某些属性 2.默认值的处理 3.空值的处理 4.支持非公共成员 5.日期处理 6.自定义序列化的字段名称
手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...
- java中final关键字
一.final修饰方法 禁止任何继承类修改它的定义,保证在继承中使方法行为保持不闲并且不会被覆盖. final修饰的方法,同意编译器针对该方法的调用转为内嵌调用.(类似c++ 中的inline?) p ...
- tc srm 636 div2 500
100的数据直接暴力就行,想多了... ac的代码: #include <iostream> #include <cstdio> #include <cstring> ...
- HDU (线段树 单点更新) I Hate It
和上一道题没什么变化,只不过把单点增减变成了单点替换,把区间求和变成了区间求最大值. #include <cstdio> #include <algorithm> using ...
- LA 4255 (拓扑排序 并查集) Guess
设这个序列的前缀和为Si(0 <= i <= n),S0 = 0 每一个符号对应两个前缀和的大小关系,然后根据这个关系拓扑排序一下. 还要注意一下前缀和相等的情况,所以用一个并查集来查询. ...