pyhton——字典、拷贝、集合、文件
字典
>>> dict1={'1':'a','2':'b','3':'c','4':'d'}>>> print(dict1['a'])Traceback (most recent call last):File "<pyshell#2>", line 1, in <module>print(dict1['a'])KeyError: 'a'>>> print(dict1['1'])a
什么类型作为键值对都可以
>>> dict2={1:'a',2:'b',3:'c'}>>> dict2[1]'a'>>> dict3={}>>> dict3{}>>> help(dict)这货是一个工厂函数Help on class dict in module builtins:class dict(object)| dict() -> new empty dictionary| dict(mapping) -> new dictionary initialized from a mapping object's| (key, value) pairs| dict(iterable) -> new dictionary initialized as if via:| d = {}| for k, v in iterable:| d[k] = v| dict(**kwargs) -> new dictionary initialized with the name=value pairs| in the keyword argument list. For example: dict(one=1, two=2)| | Methods defined here:| | __contains__(self, key, /)| True if D has a key k, else False.| | __delitem__(self, key, /)| Delete self[key].| | __eq__(self, value, /)| Return self==value.| | __ge__(self, value, /)| Return self>=value.| | __getattribute__(self, name, /)| Return getattr(self, name).| | __getitem__(...)| x.__getitem__(y) <==> x[y]| | __gt__(self, value, /)| Return self>value.| | __init__(self, /, *args, **kwargs)| Initialize self. See help(type(self)) for accurate signature.| | __iter__(self, /)| Implement iter(self).| | __le__(self, value, /)| Return self<=value.| | __len__(self, /)| Return len(self).| | __lt__(self, value, /)| Return self<value.| | __ne__(self, value, /)| Return self!=value.| | __new__(*args, **kwargs) from builtins.type| Create and return a new object. See help(type) for accurate signature.| | __repr__(self, /)| Return repr(self).| | __setitem__(self, key, value, /)| Set self[key] to value.| | __sizeof__(...)| D.__sizeof__() -> size of D in memory, in bytes| | clear(...)| D.clear() -> None. Remove all items from D.| | copy(...)| D.copy() -> a shallow copy of D| | fromkeys(iterable, value=None, /) from builtins.type| Returns a new dict with keys from iterable and values equal to value.| | get(...)| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.| | items(...)| D.items() -> a set-like object providing a view on D's items| | keys(...)| D.keys() -> a set-like object providing a view on D's keys| | pop(...)| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.| If key is not found, d is returned if given, otherwise KeyError is raised| | popitem(...)| D.popitem() -> (k, v), remove and return some (key, value) pair as a| 2-tuple; but raise KeyError if D is empty.| | setdefault(...)| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D| | update(...)| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v| In either case, this is followed by: for k in F: D[k] = F[k]| | values(...)| D.values() -> an object providing a view on D's values| | ----------------------------------------------------------------------| Data and other attributes defined here:| | __hash__ = None>>> dict3=dict((('f',70),('i',105),('s',115),('h',104)))>>> dict3{'i': 105, 'h': 104, 'f': 70, 's': 115}>>> dict4=dict(1='d',2='c')SyntaxError: keyword can't be an expression>>> dict4=dict(zyj='aaa',21='age')SyntaxError: keyword can't be an expression>>> dict4=dict(zyj='a',miss='b')>>> dict44Traceback (most recent call last):File "<pyshell#14>", line 1, in <module>dict44NameError: name 'dict44' is not defined>>> dict4{'zyj': 'a', 'miss': 'b'}>>> dict4['aa']='sss'>>> dict4{'zyj': 'a', 'aa': 'sss', 'miss': 'b'}>>> dict5=dict('ww'='ff','wr'='rew')SyntaxError: keyword can't be an expression
>>>
字典常用函数
formkeys()>>> dict1={}>>> dict1.formkeys((1,2,3))Traceback (most recent call last):File "<pyshell#20>", line 1, in <module>dict1.formkeys((1,2,3))AttributeError: 'dict' object has no attribute 'formkeys'>>> dict1.fromkeys((1,2,3)){1: None, 2: None, 3: None}>>> dict1.fromkeys((1,2,3),('one','two','three')){1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}>>> dict1=dict1.fromkeys((range(32)),'zan')>>> dict1{0: 'zan', 1: 'zan', 2: 'zan', 3: 'zan', 4: 'zan', 5: 'zan', 6: 'zan', 7: 'zan', 8: 'zan', 9: 'zan', 10: 'zan', 11: 'zan', 12: 'zan', 13: 'zan', 14: 'zan', 15: 'zan', 16: 'zan', 17: 'zan', 18: 'zan', 19: 'zan', 20: 'zan', 21: 'zan', 22: 'zan', 23: 'zan', 24: 'zan', 25: 'zan', 26: 'zan', 27: 'zan', 28: 'zan', 29: 'zan', 30: 'zan', 31: 'zan'}>>> for eachKey in dict1.keys():print(eachKey)012345678910111213141516171819202122232425262728293031>>> for eachKey in dict1.values():print(eachKey)zanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzanzan>>> for eachKey in dict1.items():print(eachKey)(0, 'zan')(1, 'zan')(2, 'zan')(3, 'zan')(4, 'zan')(5, 'zan')(6, 'zan')(7, 'zan')(8, 'zan')(9, 'zan')(10, 'zan')(11, 'zan')(12, 'zan')(13, 'zan')(14, 'zan')(15, 'zan')(16, 'zan')(17, 'zan')(18, 'zan')(19, 'zan')(20, 'zan')(21, 'zan')(22, 'zan')(23, 'zan')(24, 'zan')(25, 'zan')(26, 'zan')(27, 'zan')(28, 'zan')(29, 'zan')(30, 'zan')(31, 'zan')>>> print(dict1[43])Traceback (most recent call last):File "<pyshell#32>", line 1, in <module>print(dict1[43])KeyError: 43>>>
不想报错怎么办?
>>> print(dict1.get(32))None>>> 31 in dict1True>>> 32 in dict1False>>> 清空>>> dict1.clear()>>> dict1{}>>> a={'name':'zyj'}>>> b=a>>> a={}>>> a{}>>> b{'name': 'zyj'}>>> >>> a.clear()>>> a{}>>> b{'name': 'zyj'}
>>>
Copy函数(是浅拷贝)
>>> a={1:'a',2:'b'}>>> b=a.copy()>>> c=a>>> c{1: 'a', 2: 'b'}>>> a{1: 'a', 2: 'b'}>>> b{1: 'a', 2: 'b'}>>> id(a)150322846600>>> id(b)150323498376>>> id(c)150322846600>>> a={}>>> b{1: 'a', 2: 'b'}>>> c{1: 'a', 2: 'b'}>>> c[3]='three'>>> c{1: 'a', 2: 'b', 3: 'three'}>>> b{1: 'a', 2: 'b'}>>> a{}>>> b.pop(3)Traceback (most recent call last):File "<pyshell#62>", line 1, in <module>b.pop(3)KeyError: 3>>> b.pop(2)'b'>>> b.popitem(2)Traceback (most recent call last):File "<pyshell#64>", line 1, in <module>b.popitem(2)TypeError: popitem() takes no arguments (1 given)>>> b.popitem()(1, 'a')>>> b.setdefault(5,'five')'five'>>> a{}update>>> c{1: 'a', 2: 'b', 3: 'three'}>>> d={2:'dddd'}>>> d{2: 'dddd'}>>> a.update(d)>>> a{2: 'dddd'}>>> c.update(d)>>> c{1: 'a', 2: 'dddd', 3: 'three'}
集合
如何创建:
{}
set()工厂函数
>>> num={}>>> typr(num)Traceback (most recent call last):File "<pyshell#1>", line 1, in <module>typr(num)NameError: name 'typr' is not defined>>> type(num)<class 'dict'>>>> num={1,2,3,4}>>> type(num)<class 'set'>>>> num[2]Traceback (most recent call last):File "<pyshell#5>", line 1, in <module>num[2]TypeError: 'set' object does not support indexing>>> set1=set([1,2,3,4])>>> set1{1, 2, 3, 4}
>>>
列表去重
>>> num1=[1,2,3,3,2,5,1,5]>>> num1=list(set(num1))SyntaxError: invalid character in identifier 中文字符的问题>>> num1=list(set(num1))>>> num1[1, 2, 3, 5]自动排了序>>> num1=[1,2,3,3,2,5,1,5]>>> num1=list(set(num1))SyntaxError: invalid character in identifier>>> num1=list(set(num1))>>> num1[1, 2, 3, 5]
不可变集合frozen
>>> num3=frozenset([1,2,3,4,5])>>> num3.add(0)Traceback (most recent call last):File "<pyshell#31>", line 1, in <module>num3.add(0)AttributeError: 'frozenset' object has no attribute 'add'
文件操作
open
‘r’只读
‘w’覆盖写
‘x’如果文件已经存在,打开将引发异常
‘a’写入追加
‘b’二进制打开
‘t’以文本模式打开
‘+’可读写(可添加到其他模式中使用)
‘U’通用换行符支持
>>> f=open('F:\\python\\hano.py')>>> f<_io.TextIOWrapper name='F:\\python\\hano.py' mode='r' encoding='cp936'>f.close() python忘记关闭不会造成内存泄露,但是写入数据之后最好关闭,否则还在缓存中f.read(size=-1)读取多少个字符>>> f.read()'def hano(n,x,y,z):\n if(n==1):\n print(x,"-->",z)\n return\n hano(n-1,x,z,y)\n print(x,"-->",z)\n hano(n-1,y,x,z)\nn=int(input())\nhano(n,\'x\',\'y\',\'z\')\n \n'>>> f.read()''
文件指针指到了文件末尾
f.readline()写入模式打开,如果文件存在,则在末尾追加写入
f.write(str)将字符串写入文件
f.writelines(seq)向文件写入字符串序列seq,返回字符串的可迭代对象
f.seek(offset,from)在文件中移动文件指针,从from(0起始,1当前,2末尾)偏移offset字节
f.tell()返回当前位置
>>> f=open('F:\\python\\hano.py')>>> f.read(5)'def h'>>> f.seek(45,0)45>>> f.readline()'int(x,"-->",z)\n'>>> f.seek(0,0)0>>> for each_line in f:print(each_line)def hano(n,x,y,z):if(n==1):print(x,"-->",z)returnhano(n-1,x,z,y)print(x,"-->",z)hano(n-1,y,x,z)n=int(input())hano(n,'x','y','z')>>> f.write('i love misszhou')Traceback (most recent call last):File "<pyshell#15>", line 1, in <module>f.write('i love misszhou')io.UnsupportedOperation: not writable>>> f=open('F:\\python\\cout.txt','w')>>> f.write('misszhou 要努力')12>>> f.close()
文件系统
OS模块:
不需要关心具体的操作系统(python是跨平台的)
>>> import os>>> os.getced()Traceback (most recent call last):File "<pyshell#6>", line 1, in <module>os.getced()AttributeError: module 'os' has no attribute 'getced'>>> os.cwd()Traceback (most recent call last):File "<pyshell#7>", line 1, in <module>os.cwd()AttributeError: module 'os' has no attribute 'cwd'>>> os.getcwd()'C:\\Program Files\\Python35'>>> os.chdir('E:\\')>>> os.getcwd()'E:\\'>>> os.listdir('E:\\')['$RECYCLE.BIN', '360Downloads', 'BaiduYunDownload', 'KwDownload', 'MyDownloads', 'System Volume Information', '[LAMP兄弟连新版原创PHP视频教程].16课软件_LAMP环境安装(PHP环境搭建).rar', '[LAMP兄弟连新版原创PHP视频教程].17_在Windows系统中分别安装PHP工作环境.rar', '[LAMP兄弟连新版原创PHP视频教程].18_在Windows系统中安装集成的PHP开发环境', '[LAMP兄弟连新版原创PHP视频教程].18_在Windows系统中安装集成的PHP开发环境.rar', '[LAMP兄弟连新版原创PHP视频教程].19_Apache服务器的基本配置', '[LAMP兄弟连新版原创PHP视频教程].19_Apache服务器的基本配置.rar', '迅雷下载']>>> os.mkdir('E:\\a')>>> os.makedirs('E:\\a\\b\\c')>>> os.remove('E:\\a\\b\\tmp.txt')>>> os.remove('E:\\a')Traceback (most recent call last):File "<pyshell#15>", line 1, in <module>os.remove('E:\\a')PermissionError: [WinError 5] 拒绝访问。: 'E:\\a'>>> os.removedirs('E:\\a')Traceback (most recent call last):File "<pyshell#16>", line 1, in <module>os.removedirs('E:\\a')File "C:\Program Files\Python35\lib\os.py", line 259, in removedirsrmdir(name)OSError: [WinError 145] 目录不是空的。: 'E:\\a'>>> os.system('calc')0>>> os.curdir'.'
os.curdir (‘.’)
os.pardir (‘..’)
os.seq 输出操作系统特定的路径分割符 win \\ linux /
os.linesep win ‘\r\n’ linux ‘\n’
os.name 指代当前使用的操作系统 posix-linux nt-win mac os2 ce java
os.path模块
getatime()访问时间
getctime()创建时间
getmtime()修改时间————
格林尼治时间gmtime
当地时间localtime
>>> os.name'nt'>>> os.path.basename('E:\\A\\misszhou')'misszhou'>>> os.path.dirname('E:\\A\\misszhou.txt')'E:\\A'>>> os.path.join('A','b')'A\\b'>>> os.path.join('E:','a')'E:a'>>> os.path.join('A','B','C')'A\\B\\C'>>> os.path.join('A','B')'A\\B'>>> os.path.split('E:\\A\\B\\C')('E:\\A\\B', 'C')>>> os.path.splitext('E:\\a\\b')('E:\\a\\b', '')>>> import time>>> time.gmtime(os.path.getatime('E:\\aSyntaxError: EOL while scanning string literal>>> time.gmtime(os.path.getatime('E:\\a'))time.struct_time(tm_year=2016, tm_mon=7, tm_mday=13, tm_hour=13, tm_min=1, tm_sec=12, tm_wday=2, tm_yday=195, tm_isdst=0)>>> time.localtime(os.path.getatime('E:\\a'))time.struct_time(tm_year=2016, tm_mon=7, tm_mday=13, tm_hour=21, tm_min=1, tm_sec=12, tm_wday=2, tm_yday=195, tm_isdst=0)
exists(path)判断指定路径或文件是否存在
isabs(path)判断制定路径是否是绝对路径
isdir(path)判断制定路径是否存在且是一个目录
isfile(path)。。文件
islink(path)。。符号链接
ismount(path)。。挂载点
pyhton——字典、拷贝、集合、文件相关推荐
- python 字典+列表集合+文件读取
字典示例 ************************ 各地食品的三级菜单************************* 1.使用字典嵌套字典 2.采用死循环思路 3.对字典 循环打印 只可得 ...
- python day2 python基础 列表、元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码...
本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 ...
- 9. python 入门教程快速复习,序列,数值类型,字符串方法,列表、集合、字典方法,文件操作,解析式
文章目录 序列 数值类型 字符串方法大军 列表,集合,字典常用的方法 python 文件操作 解析式 写在后面 序列 序列是 python 中非常重要的一个概念,一个序列包含如下特征: 序列有顺序: ...
- 刻意练习:Python基础 -- Task06. 字典与集合
背景 我们准备利用17天时间,将 "Python基础的刻意练习" 分为如下任务: Task01:变量.运算符与数据类型(1day) Task02:条件与循环(1day) Task0 ...
- Day2 - Python基础2 列表、字典、集合
Python之路,Day2 - Python基础2 本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过 ...
- Day2 - Python基础2 列表、字典、集合 --转自金角大王
Day2 - Python基础2 列表.字典.集合 --转自金角大王 Posted on 2018-01-24 13:23 Byd_lei 阅读(41) 评论(0) 编辑 收藏 本节内容 列表.元组 ...
- 【python第四章——序列(列表、元组、字典、集合、字符串、正则)】
python第四章--序列 第四章--序列 4.1列表 4.2元组 4.3字典 4.4集合 4.5字符串(重要) 4.6正则表达式 第四章--序列 概念:序列指一块可存放多个值的连续内存空间,这些值按 ...
- OC基础第四讲--字符串、数组、字典、集合的常用方法
OC基础第四讲--字符串.数组.字典.集合的常用方法 字符串.数组.字典.集合有可变和不可变之分.以字符串为例,不可变字符串本身值不能改变,必须要用相应类型来接收返回值:而可变字符串调用相应地方法后, ...
- iOS 开发 OC编程 字典和集合 排序方法
// // main.m // oc- 05 字典和集合 // // Created by dllo on 15/10/29. // Copyright (c) 2015年 dllo. All ...
- python基础语法合集-Python基础语法(四)—列表、元组、字典、集合、字符串
列表 基本概念列表是有序的元素集合,所有元素放在一对中括号中,用逗号隔开,没有长度限制: 列表索引值以0为开始值,-1为从未尾的开始位置. 列表可以使用+操作符进行拼接,使用*表示重复. 当列表元素增 ...
最新文章
- Nginx源码安装及应用
- C 整数反转
- 标准化工作导则2020_最新版 GB/T 1.12020 标准化工作导则 第 1 部分:标准化文件的结构和起草规则标准解读...
- C语言 BMP24位变单色,怎么将24位色BMP图片改为单色或16色?(2)
- 机器学习 | 回归评估指标
- Python装饰器的实现和万能装饰器
- Python中表达式和语句及for、while循环练习
- 海底捞发布公告 预计去年最高亏损45亿
- Twips 缇的含义[来自网络]
- cookie里面用到的关键字_Java的理解角度-关键字篇
- C语言编程题:求一元二次方程组的根
- opta球员大数据预测胜负_大数据预测4个特征,10个典型行业
- 耗时一个月,总结的Linux C++后台开发学习路线(已签腾讯sp,附学习资料)
- 关于永洪科技官网被再次冒充事件的详细说明
- 【OJ每日一练】1044 - 下落又弹起的小球
- 仿微信.QQ聊天界面
- 操作系统原理,物理内存“扩充”技术,内存紧缩,覆盖,交换,虚拟内存思想
- python怎么从excel获取数据_python如何读取excel表数据
- 【算法】几个数组拆分题的算法(动态规划,矩阵递归和同余问题)
- 解决使用JdbcTemplate查询数据产生的异常:EmptyResultDataAccessException: Incorrect result size: expected 1, actual