pyhton——字典、拷贝、集合、文件

来源:互联网 发布:再见金华站 知乎 编辑:程序博客网 时间:2024/06/03 12:33

字典

>>> 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)在文件中移动文件指针,从from0起始,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)        return    hano(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 removedirs    rmdir(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:\\a     SyntaxError: 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)。。挂载点


0 0
原创粉丝点击