1、文件操作
-
python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。
得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
返回指定目录下的所有文件和目录名:os.listdir()
函数用来删除一个文件:os.remove()
删除多个目录:os.removedirs(r“c:\python”)
检验给出的路径是否是一个文件:os.path.isfile()
检验给出的路径是否是一个目录:os.path.isdir()
判断是否是绝对路径:os.path.isabs()
检验给出的路径是否真地存:os.path.exists()
返回一个路径的目录名和文件名:os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt')
分离扩展名:os.path.splitext()
获取路径名:os.path.dirname()
获取文件名:os.path.basename()
运行shell命令: os.system()
读取和设置环境变量:os.getenv() 与os.putenv()
给出当前平台使用的行终止符:os.linesep Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
指示你正在使用的平台:os.name 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
重命名:os.rename(old, new)
创建多级目录:os.makedirs(r“c:\python\test”)
创建单个目录:os.mkdir(“test”)
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
终止当前进程:os.exit()
获取文件大小:os.path.getsize(filename)
- 文件操作:
os.mknod("test.txt") 创建空文件
fp = open("test.txt",w) 直接打开一个文件,如果文件不存在则创建文件
关于open 模式:
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
fp.read([size]) #size为读取的长度,以byte为单位
fp.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
fp.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
fp.write(str) #把str写到文件中,write()并不会在str后加上一个换行符
fp.writelines(seq) #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。
fp.close() #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。 如果一个文件在关闭后还对其进行操作会产生ValueError
fp.flush() #把缓冲区的内容写入硬盘
fp.fileno() #返回一个长整型的”文件标签“
fp.isatty() #文件是否是一个终端设备文件(unix系统中的)
fp.tell() #返回文件操作标记的当前位置,以文件的开头为原点
fp.next() #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。
fp.seek(offset[,whence]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。
fp.truncate([size]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。
- 目录操作:
os.mkdir("file") 创建目录
复制文件:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在
重命名文件(目录)
os.rename("oldname","newname") 文件或目录都是使用这条命令
移动文件(目录)
shutil.move("oldpos","newpos")
删除文件
os.remove("file")
删除目录
os.rmdir("dir")只能删除空目录
shutil.rmtree("dir") 空目录、有内容的目录都可以删
转换目录
os.chdir("path") 换路径
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1 with open('log','r') as f: 2 3 ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
1 with open('log1') as obj1, open('log2') as obj2: 2 pass
- 相关例子
①、 将文件夹下所有图片名称加上'_fc'
python代码:
1 # -*- coding:utf-8 -*- 2 import re 3 import os 4 import time 5 #str.split(string)分割字符串 6 #'连接符'.join(list) 将列表组成字符串 7 def change_name(path): 8 global i 9 if not os.path.isdir(path) and not os.path.isfile(path): 10 return False 11 if os.path.isfile(path): 12 file_path = os.path.split(path) #分割出目录与文件 13 lists = file_path[1].split('.') #分割出文件与文件扩展名 14 file_ext = lists[-1] #取出后缀名(列表切片操作) 15 img_ext = ['bmp','jpeg','gif','psd','png','jpg'] 16 if file_ext in img_ext: 17 os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext) 18 i+=1 #注意这里的i是一个陷阱 19 #或者 20 #img_ext = 'bmp|jpeg|gif|psd|png|jpg' 21 #if file_ext in img_ext: 22 # print('ok---'+file_ext) 23 elif os.path.isdir(path): 24 for x in os.listdir(path): 25 change_name(os.path.join(path,x)) #os.path.join()在路径处理上很有用 28 img_dir = 'D:\\xx\\xx\\images' 29 img_dir = img_dir.replace('\\','/') 30 start = time.time() 31 i = 0 32 change_name(img_dir) 33 c = time.time() - start 34 print('程序运行耗时:%0.2f'%(c)) 35 print('总共处理了 %s 张图片'%(i)) 37 输出结果: 39 程序运行耗时:0.11 40 总共处理了 109 张图片
②、
1)打开文件,得到文件句柄并赋值给一个变量
2)通过句柄对文件进行操作
3)关闭文件
文件
代码
1 f = open('lyrics') #打开文件 2 first_line = f.readline() 3 print('first line:',first_line) #读一行 4 print('我是分隔线'.center(50,'-')) 5 data = f.read()# 读取剩下的所有内容,文件大时不要用 6 print(data) #打印文件 7 f.close() #关闭文件
2、Number(数字)
Python3 支持 int、float、bool、complex(复数)。
在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
像大多数语言一样,数值类型的赋值和计算都是很直观的。
内置的type()函数可以用来查询变量所指的对象类型。
>>> a, b, c, d = 20, 5.5, True, 4+3j >>> print(type(a), type(b), type(c), type(d)) <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
注意:在Python2中是没有布尔型的,它用数字0表示False,用1表示True。到Python3中,把True和False定义成关键字了,但它们的值还是1和0,它们可以和数字相加。
当你指定一个值时,Number 对象就会被创建:
var1 = 1
var2 = 10
您也可以使用del语句删除一些对象引用。
del语句的语法是:
del var1[,var2[,var3[....,varN]]]]
您可以通过使用del语句删除单个或多个对象。例如:
del var
del var_a, var_b
数值运算
>>> 5 + 4 # 加法 9 >>> 4.3 - 2 # 减法 2.3 >>> 3 * 7 # 乘法 21 >>> 2 / 4 # 除法,得到一个浮点数 0.5 >>> 2 // 4 # 除法,得到一个整数 0 >>> 17 % 3 # 取余 2 >>> 2 ** 5 # 乘方 32
注意:
- 1、Python可以同时为多个变量赋值,如a, b = 1, 2。
- 2、一个变量可以通过赋值指向不同类型的对象。
- 3、数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。
- 4、在混合计算时,Python会把整型转换成为浮点数。
数值类型实例
int | float | complex |
---|---|---|
10 | 0.0 | 3.14j |
100 | 15.20 | 45.j |
-786 | -21.9 | 9.322e-36j |
080 | 32.3+e18 | .876j |
-0490 | -90. | -.6545+0J |
-0x260 | -32.54e100 | 3e+26J |
0x69 | 70.2-E12 | 4.53e-7j |
Python还支持复数,复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型
3、String(字符串)
Python中的字符串用单引号(')或双引号(")括起来,同时使用反斜杠(\)转义特殊字符。
字符串的截取的语法格式如下:
变量[头下标:尾下标]
索引值以 0 为开始值,-1 为从末尾的开始位置。
加号 (+) 是字符串的连接符, 星号 (*) 表示复制当前字符串,紧跟的数字为复制的次数。实例如下:
#!/usr/bin/python3str = 'Runoob' print (str) # 输出字符串 print (str[0:-1]) # 输出第一个个到倒数第二个的所有字符 print (str[0]) # 输出字符串第一个字符 print (str[2:5]) # 输出从第三个开始到第五个的字符 print (str[2:]) # 输出从第三个开始的后的所有字符 print (str * 2) # 输出字符串两次 print (str + "TEST") # 连接字符串
执行以上程序会输出如下结果:
Runoob
Runoo
R
noo
noob
RunoobRunoob RunoobTEST
Python 使用反斜杠(\)转义特殊字符,如果你不想让反斜杠发生转义,可以在字符串前面添加一个 r,表示原始字符串:
>>> print('Ru\noob') Ru oob >>> print(r'Ru\noob') Ru\noob >>>
另外,反斜杠(\)可以作为续行符,表示下一行是上一行的延续。也可以使用 """...""" 或者 '''...''' 跨越多行。
注意,Python 没有单独的字符类型,一个字符就是长度为1的字符串。
>>> word = 'Python' >>> print(word[0], word[5]) P n >>> print(word[-1], word[-6]) n P
与 C 字符串不同的是,Python 字符串不能被改变。向一个索引位置赋值,比如word[0] = 'm'会导致错误。
注意:
- 1、反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
- 2、字符串可以用+运算符连接在一起,用*运算符重复。
- 3、Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
- 4、Python中的字符串不能改变。
4、List(列表)
List(列表) 是 Python 中使用最频繁的数据类型。
列表可以完成大多数集合类的数据结构实现。列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。
列表是写在方括号([])之间、用逗号分隔开的元素列表。
和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表。
列表截取的语法格式如下:
变量[头下标:尾下标]
索引值以 0 为开始值,-1 为从末尾的开始位置。
加号(+)是列表连接运算符,星号(*)是重复操作。如下实例:
#!/usr/bin/python3list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ] tinylist = [123, 'runoob'] print (list) # 输出完整列表 print (list[0]) # 输出列表第一个元素 print (list[1:3]) # 从第二个开始输出到第三个元素 print (list[2:]) # 输出从第三个元素开始的所有元素 print (tinylist * 2) # 输出两次列表 print (list + tinylist) # 连接列表
以上实例输出结果:
['abcd', 786, 2.23, 'runoob', 70.2] abcd [786, 2.23] [2.23, 'runoob', 70.2] [123, 'runoob', 123, 'runoob'] ['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']
与Python字符串不一样的是,列表中的元素是可以改变的:
>>> a = [1, 2, 3, 4, 5, 6] >>> a[0] = 9 >>> a[2:5] = [13, 14, 15] >>> a [9, 2, 13, 14, 15, 6] >>> a[2:5] = [] # 删除 >>> a [9, 2, 6]
List内置了有很多方法,例如append()、pop()等等,
① 切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] print (name_list[ 0 : 3 ]) #取下标0至下标3之间的元素,包括0,不包括3 #['Alex', 'Tenglan', 'Eric'] print (name_list[: 3 ]) #:前什么都不写,表示从0开始,效果跟上句一样 #['Alex', 'Tenglan', 'Eric'] print (name_list[ 3 :]) #:后什么不写,表示取值到最后 #['Rain', 'Tom', 'Amy'] print (name_list[:]) #:前后都不写,表示取值所有 #['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] print (name_list[ - 3 : - 1 ]) #从-3开始到-1,包括-3,不包括-1 #['Rain', 'Tom'] print (name_list[ 1 : - 1 ]) #从1开始到-1,下标有正有负时,正数在前负数在后 #['Tenglan', 'Eric', 'Rain', 'Tom'] print (name_list[:: 2 ]) #2表示,每个1个元素,就取一个 #['Alex', 'Eric', 'Tom'] #注:[-1:0] [0:0] [-1:2] 都是空 |
② 追加
1 2 3 4 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] name_list.append( "new" ) #append追加,加到最后,只能添加一个 print (name_list) #['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'new'] |
③ 插入
1 2 3 4 | #插入 name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] name_list.insert( 3 , "new" ) #insert插入,把"new"加到下标3的位置 print (name_list) |
④ 修改
1 2 3 4 | #修改 name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] name_list[ 2 ] = "lzl" #把下标2的字符串换成lzl print (name_list) |
⑤ 删除
1 2 3 4 5 6 7 8 9 10 11 | #3种删除方式 name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] del name_list[ 3 ] #del删除,指定要删除的下标 print (name_list) #['Alex', 'Tenglan', 'Eric', 'Tom', 'Amy'] name_list.remove( "Tenglan" ) #remove删除,指定要删除的字符 print (name_list) #['Alex', 'Eric', 'Tom', 'Amy'] name_list.pop() #pop删除,删除列表最后一个值 print (name_list) #['Alex', 'Eric', 'Tom'] |
⑥ 扩展
1 2 3 4 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] age_list = [ 11 , 22 , 33 ] name_list.extend(age_list) #extend扩展,把列表age_list添加到name_list列表 print (name_list) |
⑦ 拷贝
1 2 3 4 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] copy_list = name_list.copy() #copy拷贝,对列表进行复制 print (copy_list) #注:博客最下有关于深浅copy的详细区分 |
⑧ 统计
1 2 3 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Amy" , "Tom" , "Amy" ] print (name_list.count( "Amy" )) #count统计,统计列表Amy的个数 #2 |
⑨ 排序和翻转
1 2 3 4 5 6 7 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" , "1" , "2" , "3" ] name_list.sort() #sort排序,对列表进行排序 print (name_list) #['1', '2', '3', 'Alex', 'Amy', 'Eric', 'Rain', 'Tenglan', 'Tom'] name_list.reverse() #reverse翻转,对列表进行翻转 print (name_list) #['Tom', 'Tenglan', 'Rain', 'Eric', 'Amy', 'Alex', '3', '2', '1'] |
⑩ 获取下标
1 2 3 | name_list = [ "Alex" , "Tenglan" , "Eric" , "Rain" , "Tom" , "Amy" ] print (name_list.index( "Tenglan" )) #index索引,获取字符的下标 #1 |
扩展
1 class list(object): 2 """ 3 list() -> new empty list 4 list(iterable) -> new list initialized from iterable's items 5 """ 6 def append(self, p_object): # real signature unknown; restored from __doc__ 7 """ L.append(object) -- append object to end """ 8 pass 9 10 def count(self, value): # real signature unknown; restored from __doc__ 11 """ L.count(value) -> integer -- return number of occurrences of value """ 12 return 0 13 14 def extend(self, iterable): # real signature unknown; restored from __doc__ 15 """ L.extend(iterable) -- extend list by appending elements from the iterable """ 16 pass 17 18 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 19 """ 20 L.index(value, [start, [stop]]) -> integer -- return first index of value. 21 Raises ValueError if the value is not present. 22 """ 23 return 0 24 25 def insert(self, index, p_object): # real signature unknown; restored from __doc__ 26 """ L.insert(index, object) -- insert object before index """ 27 pass 28 29 def pop(self, index=None): # real signature unknown; restored from __doc__ 30 """ 31 L.pop([index]) -> item -- remove and return item at index (default last). 32 Raises IndexError if list is empty or index is out of range. 33 """ 34 pass 35 36 def remove(self, value): # real signature unknown; restored from __doc__ 37 """ 38 L.remove(value) -- remove first occurrence of value. 39 Raises ValueError if the value is not present. 40 """ 41 pass 42 43 def reverse(self): # real signature unknown; restored from __doc__ 44 """ L.reverse() -- reverse *IN PLACE* """ 45 pass 46 47 def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ 48 """ 49 L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 50 cmp(x, y) -> -1, 0, 1 51 """ 52 pass 53 54 def __add__(self, y): # real signature unknown; restored from __doc__ 55 """ x.__add__(y) <==> x+y """ 56 pass 57 58 def __contains__(self, y): # real signature unknown; restored from __doc__ 59 """ x.__contains__(y) <==> y in x """ 60 pass 61 62 def __delitem__(self, y): # real signature unknown; restored from __doc__ 63 """ x.__delitem__(y) <==> del x[y] """ 64 pass 65 66 def __delslice__(self, i, j): # real signature unknown; restored from __doc__ 67 """ 68 x.__delslice__(i, j) <==> del x[i:j] 69 70 Use of negative indices is not supported. 71 """ 72 pass 73 74 def __eq__(self, y): # real signature unknown; restored from __doc__ 75 """ x.__eq__(y) <==> x==y """ 76 pass 77 78 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getitem__(self, y): # real signature unknown; restored from __doc__ 83 """ x.__getitem__(y) <==> x[y] """ 84 pass 85 86 def __getslice__(self, i, j): # real signature unknown; restored from __doc__ 87 """ 88 x.__getslice__(i, j) <==> x[i:j] 89 90 Use of negative indices is not supported. 91 """ 92 pass 93 94 def __ge__(self, y): # real signature unknown; restored from __doc__ 95 """ x.__ge__(y) <==> x>=y """ 96 pass 97 98 def __gt__(self, y): # real signature unknown; restored from __doc__ 99 """ x.__gt__(y) <==> x>y """ 100 pass 101 102 def __iadd__(self, y): # real signature unknown; restored from __doc__ 103 """ x.__iadd__(y) <==> x+=y """ 104 pass 105 106 def __imul__(self, y): # real signature unknown; restored from __doc__ 107 """ x.__imul__(y) <==> x*=y """ 108 pass 109 110 def __init__(self, seq=()): # known special case of list.__init__ 111 """ 112 list() -> new empty list 113 list(iterable) -> new list initialized from iterable's items 114 # (copied from class doc) 115 """ 116 pass 117 118 def __iter__(self): # real signature unknown; restored from __doc__ 119 """ x.__iter__() <==> iter(x) """ 120 pass 121 122 def __len__(self): # real signature unknown; restored from __doc__ 123 """ x.__len__() <==> len(x) """ 124 pass 125 126 def __le__(self, y): # real signature unknown; restored from __doc__ 127 """ x.__le__(y) <==> x<=y """ 128 pass 129 130 def __lt__(self, y): # real signature unknown; restored from __doc__ 131 """ x.__lt__(y) <==> x<y """ 132 pass 133 134 def __mul__(self, n): # real signature unknown; restored from __doc__ 135 """ x.__mul__(n) <==> x*n """ 136 pass 137 138 @staticmethod # known case of __new__ 139 def __new__(S, *more): # real signature unknown; restored from __doc__ 140 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 141 pass 142 143 def __ne__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ne__(y) <==> x!=y """ 145 pass 146 147 def __repr__(self): # real signature unknown; restored from __doc__ 148 """ x.__repr__() <==> repr(x) """ 149 pass 150 151 def __reversed__(self): # real signature unknown; restored from __doc__ 152 """ L.__reversed__() -- return a reverse iterator over the list """ 153 pass 154 155 def __rmul__(self, n): # real signature unknown; restored from __doc__ 156 """ x.__rmul__(n) <==> n*x """ 157 pass 158 159 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 160 """ x.__setitem__(i, y) <==> x[i]=y """ 161 pass 162 163 def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ 164 """ 165 x.__setslice__(i, j, y) <==> x[i:j]=y 166 167 Use of negative indices is not supported. 168 """ 169 pass 170 171 def __sizeof__(self): # real signature unknown; restored from __doc__ 172 """ L.__sizeof__() -- size of L in memory, in bytes """ 173 pass 174 175 __hash__ = None 176 177 list 178 179 list
注意:
- 1、与字符串一样,元组的元素不能修改。
- 2、元组也可以被索引和切片,方法一样。
- 3、注意构造包含0或1个元素的元组的特殊语法规则。
- 4、元组也可以使用+操作符进行拼接。
5、Set(集合)
集合(set)是一个无序不重复元素的序列。
基本功能是进行成员关系测试和删除重复元素。
可以使用大括号({})或者 set()函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
#!/usr/bin/python3student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # 输出集合,重复的元素被自动去掉 # 成员测试 if('Rose' in student) : print('Rose 在集合中') else : print('Rose 不在集合中') # set可以进行集合运算 a = set('abracadabra') b = set('alacazam') print(a) print(a - b) # a和b的差集 print(a | b) # a和b的并集 print(a & b) # a和b的交集 print(a ^ b) # a和b中不同时存在的元素
以上实例输出结果:
{'Jack', 'Rose', 'Mary', 'Jim', 'Tom'} Rose 在集合中 {'r', 'b', 'a', 'c', 'd'} {'r', 'b', 'd'} {'a', 'l', 'z', 'b', 'm', 'd', 'r', 'c'} {'a', 'c'} {'l', 'z', 'b', 'm', 'd', 'r'}
6、Dictionary(字典)
字典(dictionary)是Python中另一个非常有用的内置数据类型。
列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。
键(key)必须使用不可变类型。
在同一个字典中,键(key)必须是唯一的。
#!/usr/bin/python3dict = {} dict['one'] = "1 - 菜鸟教程" dict[2] = "2 - 菜鸟工具" tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'} print (dict['one']) # 输出键为 'one' 的值 print (dict[2]) # 输出键为 2 的值 print (tinydict) # 输出完整的字典 print (tinydict.keys()) # 输出所有键 print (tinydict.values()) # 输出所有值
以上实例输出结果:
1 - 菜鸟教程 2 - 菜鸟工具 {'name': 'runoob', 'site': 'www.runoob.com', 'code': 1} dict_keys(['name', 'site', 'code']) dict_values(['runoob', 'www.runoob.com', 1])
构造函数 dict() 可以直接从键值对序列中构建字典如下:
>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)]) {'Taobao': 3, 'Runoob': 1, 'Google': 2} >>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} >>> dict(Runoob=1, Google=2, Taobao=3) {'Taobao': 3, 'Runoob': 1, 'Google': 2}
另外,字典类型也有一些内置的函数,例如clear()、keys()、values()等。
2、字典类常用功能:
① 增加
1 2 3 | info_dic = { 'stu1101' : "TengLan Wu" , 'stu1102' : "LongZe Luola" , 'stu1103' : "XiaoZe Maliya" ,} info_dic[ 'stu1104' ] = "JingKong Cang" #增加 print (info_dic) |
② 修改
1 2 3 | info_dic = { 'stu1101' : "TengLan Wu" , 'stu1102' : "LongZe Luola" , 'stu1103' : "XiaoZe Maliya" ,} info_dic[ "stu1101" ] = "Jingkong Cang" #有相应的key时为修改,没有为增加 print (info_dic) |
③ 删除
1 2 3 4 5 6 7 8 9 10 11 12 | #3种删除方式 info_dic = { 'stu1101' : "TengLan Wu" , 'stu1102' : "LongZe Luola" , 'stu1103' : "XiaoZe Maliya" ,} info_dic.pop( 'stu1101' ) #pop删除,指定删除的key print (info_dic) #{'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola'} del info_dic[ 'stu1102' ] #del删除,指定删除的key print (info_dic) #{'stu1103': 'XiaoZe Maliya'} info_dic = { 'stu1101' : "TengLan Wu" , 'stu1102' : "LongZe Luola" , 'stu1103' : "XiaoZe Maliya" ,} info_dic.popitem() #随机删除,没卵用 print (info_dic) #{'stu1101': 'TengLan Wu', 'stu1103': 'XiaoZe Maliya'} |
④ 查找value值
1 2 3 4 5 | info_dic = { 'stu1101' : "TengLan Wu" , 'stu1102' : "LongZe Luola" , 'stu1103' : "XiaoZe Maliya" ,} print (info_dic.get( 'stu1102' )) #get查找,通过key查找value值 #LongZe Luola print (info_dic[ 'stu1102' ]) #通过key直接查找,但是如果输入查找的key不存在的话,就会报错,get则不会 #LongZe Luola |
⑤ 字典多级嵌套
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | av_catalog = { "欧美" :{ "www.youporn.com" : [ "很多免费的,世界最大的" , "质量一般" ], "www.pornhub.com" : [ "很多免费的,也很大" , "质量比yourporn高点" ], "letmedothistoyou.com" : [ "多是自拍,高质量图片很多" , "资源不多,更新慢" ], "x-art.com" :[ "质量很高,真的很高" , "全部收费,屌比请绕过" ] }, "日韩" :{ "tokyo-hot" :[ "质量怎样不清楚,个人已经不喜欢日韩范了" , "听说是收费的" ] }, "大陆" :{ "1024" :[ "全部免费,真好,好人一生平安" , "服务器在国外,慢" ] } } av_catalog[ "大陆" ][ "1024" ][ 1 ] + = ",可以用爬虫爬下来" print (av_catalog[ "大陆" ][ "1024" ]) #['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来'] |
⑥ 循环
1 2 3 4 5 6 7 8 9 10 11 | info_dic = { 'stu1101' : "TengLan Wu" , 'stu1102' : "LongZe Luola" , 'stu1103' : "XiaoZe Maliya" ,} for stu_nu in info_dic: print (stu_nu,info_dic[stu_nu]) #循环默认提取的是key #stu1103 XiaoZe Maliya #stu1101 TengLan Wu #stu1102 LongZe Luola for k,v in info_dic.items(): #先把dict生成list,数据量大的时候费时,不建议使用 print (k,v) #stu1103 XiaoZe Maliya #stu1101 TengLan Wu #stu1102 LongZe Luola |
3、扩展
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除内容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 浅拷贝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根据key获取值,d是默认值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有项的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 项可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 获取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 获取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有项,只是将内容保存至view对象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict
注意:
- 1、字典是一种映射类型,它的元素是键值对。
- 2、字典的关键字必须为不可变类型,且不能重复。
- 3、创建空字典使用 { }。
7、Python数据类型转换
有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。
以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。
函数 | 描述 |
---|---|
int(x [,base]) | 将x转换为一个整数 |
float(x) | 将x转换到一个浮点数 |
complex(real [,imag]) | 创建一个复数 |
str(x) | 将对象 x 转换为字符串 |
repr(x) | 将对象 x 转换为表达式字符串 |
eval(str) | 用来计算在字符串中的有效Python表达式,并返回一个对象 |
tuple(s) | 将序列 s 转换为一个元组 |
list(s) | 将序列 s 转换为一个列表 |
set(s) | 转换为可变集合 |
dict(d) | 创建一个字典。d 必须是一个序列 (key,value)元组。 |
frozenset(s) | 转换为不可变集合 |
chr(x) | 将一个整数转换为一个字符 |
unichr(x) | 将一个整数转换为Unicode字符 |
ord(x) | 将一个字符转换为它的整数值 |
hex(x) | 将一个整数转换为一个十六进制字符串 |
oct(x) | 将一个整数转换为一个八进制字符串 |
8、字符编码与转码
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除内容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 浅拷贝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根据key获取值,d是默认值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有项的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 项可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 获取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 获取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有项,只是将内容保存至view对象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除内容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 浅拷贝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根据key获取值,d是默认值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有项的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 项可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 获取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 获取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有项,只是将内容保存至view对象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict
9、元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
语法
1 | names = ( "alex" , "jack" , "eric" ) |
它只有2个方法,一个是count,一个是index,完毕。
程序练习
请闭眼写出以下程序。
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
1 #!/usr/bin/env/python 2 import sys,os,getpass 3 product_list=[('crisp',10), 4 ('chocolate',50), 5 ('cake',100), 6 ('tea',10), 7 ('bread',10), 8 ('chicken',60), 9 ('shrimp',200)] #定义产品列表 10 print(product_list) 11 shopping_list = [] #定义购物车列表 12 salary = input("input your salary:") #输入现有的金额 13 if salary.isdigit(): #判断输入的金额是否是数字 14 salary = int(salary) # 如果是把数字转换成整型 15 while True: #如果为真 16 print("-------------product list---------------") 17 for index ,item in enumerate(product_list): #遍历产品列表中的中的数据,并加上编号。 18 print(index,item) #打印编号和产品列表中的产品 19 user_choice = input("choice the product what you want:") #输入选购的产品 20 if user_choice.isdigit():#如果用户选择的是数字 21 user_choice=int(user_choice)#把数字转换成整型 22 if user_choice < len(product_list) and user_choice>=0:#如果选择的数字编号小于产品列表的长度并且用户的选择的数字编号大于或等于0 23 p_item = product_list[user_choice] #定义产品列表中被选择的产品作为一个数组 24 if p_item[1] <= salary:#如果输入的产品的价格小于或等于现有资金 25 shopping_list.append(p_item)#购物列表中加一个商品 26 salary-=p_item[1]#现有资金-被选商品的资金传到salary里 27 print ("Added %s into shopping cart ,your current balance is %d " %(p_item, salary))#打印出添添加的商品和资金 28 else: 29 print("Sorry,Your balance is not enough")#否则提示余额不足 30 else: 31 print("product code [%s] is not exist." % user_choice)# 否则打印出产品不存在 32 elif user_choice == 'q':#其他如果用户输入 33 print("----------shopping list--------------")#打印出shopping list 34 for p in shopping_list:# 35 print(p)#循环打印出shoppinglist 36 print("your current balance: %s " % salary)#打印出你的余额 37 break