知名网站建设公,成都网站建设 冠辰,开发一个app要多久,电邮注册网站1、文件操作 python中对文件、文件夹#xff08;文件操作函数#xff09;的操作需要涉及到os模块和shutil模块。 得到当前工作目录#xff0c;即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove(…1、文件操作 python中对文件、文件夹文件操作函数的操作需要涉及到os模块和shutil模块。 得到当前工作目录即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录os.removedirsr“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\nLinux使用\n而Mac使用\r 指示你正在使用的平台os.name 对于Windows它是nt而对于Linux/Unix用户它是posix 重命名os.renameold new 创建多级目录os.makedirsr“c\python\test” 创建单个目录os.mkdir“test” 获取文件属性os.statfile 修改文件权限与时间戳os.chmodfile 终止当前进程os.exit 获取文件大小os.path.getsizefilename 文件操作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 re3 import os4 import time5 #str.split(string)分割字符串6 #连接符.join(list) 将列表组成字符串7 def change_name(path):8 global i9 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 i1 #注意这里的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, 43j 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会把整型转换成为浮点数。数值类型实例 intfloatcomplex100.03.14j10015.2045.j-786-21.99.322e-36j08032.3e18.876j-0490-90.-.65450J-0x260-32.54e1003e26J0x6970.2-E124.53e-7jPython还支持复数复数由实数部分和虚数部分构成可以用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(rRu\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 list4 list(iterable) - new list initialized from iterables items5 6 def append(self, p_object): # real signature unknown; restored from __doc__7 L.append(object) -- append object to end 8 pass9 10 def count(self, value): # real signature unknown; restored from __doc__11 L.count(value) - integer -- return number of occurrences of value 12 return 013 14 def extend(self, iterable): # real signature unknown; restored from __doc__15 L.extend(iterable) -- extend list by appending elements from the iterable 16 pass17 18 def index(self, value, startNone, stopNone): # 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 024 25 def insert(self, index, p_object): # real signature unknown; restored from __doc__26 L.insert(index, object) -- insert object before index 27 pass28 29 def pop(self, indexNone): # 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 pass35 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 pass42 43 def reverse(self): # real signature unknown; restored from __doc__44 L.reverse() -- reverse *IN PLACE* 45 pass46 47 def sort(self, cmpNone, keyNone, reverseFalse): # real signature unknown; restored from __doc__48 49 L.sort(cmpNone, keyNone, reverseFalse) -- stable sort *IN PLACE*;50 cmp(x, y) - -1, 0, 151 52 pass53 54 def __add__(self, y): # real signature unknown; restored from __doc__55 x.__add__(y) xy 56 pass57 58 def __contains__(self, y): # real signature unknown; restored from __doc__59 x.__contains__(y) y in x 60 pass61 62 def __delitem__(self, y): # real signature unknown; restored from __doc__63 x.__delitem__(y) del x[y] 64 pass65 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 pass73 74 def __eq__(self, y): # real signature unknown; restored from __doc__75 x.__eq__(y) xy 76 pass77 78 def __getattribute__(self, name): # real signature unknown; restored from __doc__79 x.__getattribute__(name) x.name 80 pass81 82 def __getitem__(self, y): # real signature unknown; restored from __doc__83 x.__getitem__(y) x[y] 84 pass85 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 pass93 94 def __ge__(self, y): # real signature unknown; restored from __doc__95 x.__ge__(y) xy 96 pass97 98 def __gt__(self, y): # real signature unknown; restored from __doc__99 x.__gt__(y) xy
100 pass
101
102 def __iadd__(self, y): # real signature unknown; restored from __doc__
103 x.__iadd__(y) xy
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 iterables 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) xy
128 pass
129
130 def __lt__(self, y): # real signature unknown; restored from __doc__
131 x.__lt__(y) xy
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 View Code 注意 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(Runoob1, Google2, Taobao3) {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 dictionary4 dict(mapping) - new dictionary initialized from a mapping objects5 (key, value) pairs6 dict(iterable) - new dictionary initialized as if via:7 d {}8 for k, v in iterable:9 d[k] v10 dict(**kwargs) - new dictionary initialized with the namevalue pairs11 in the keyword argument list. For example: dict(one1, two2)12 13 14 def clear(self): # real signature unknown; restored from __doc__15 清除内容 16 D.clear() - None. Remove all items from D. 17 pass18 19 def copy(self): # real signature unknown; restored from __doc__20 浅拷贝 21 D.copy() - a shallow copy of D 22 pass23 24 staticmethod # known case25 def fromkeys(S, vNone): # 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 pass31 32 def get(self, k, dNone): # 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 pass36 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 False41 42 def items(self): # real signature unknown; restored from __doc__43 所有项的列表形式 44 D.items() - list of Ds (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 pass51 52 def iterkeys(self): # real signature unknown; restored from __doc__53 key可迭代 54 D.iterkeys() - an iterator over the keys of D 55 pass56 57 def itervalues(self): # real signature unknown; restored from __doc__58 value可迭代 59 D.itervalues() - an iterator over the values of D 60 pass61 62 def keys(self): # real signature unknown; restored from __doc__63 所有的key列表 64 D.keys() - list of Ds keys 65 return []66 67 def pop(self, k, dNone): # 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 raised72 73 pass74 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 a79 2-tuple; but raise KeyError if D is empty.80 81 pass82 83 def setdefault(self, k, dNone): # 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 pass87 88 def update(self, ENone, **F): # known special case of dict.update89 更新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] v97 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 Ds 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 Ds 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 Ds keys
113 pass
114
115 def viewvalues(self): # real signature unknown; restored from __doc__
116 D.viewvalues() - an object providing a view on Ds 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) xy
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) xy
145 pass
146
147 def __gt__(self, y): # real signature unknown; restored from __doc__
148 x.__gt__(y) xy
149 pass
150
151 def __init__(self, seqNone, **kwargs): # known special case of dict.__init__
152
153 dict() - new empty dictionary
154 dict(mapping) - new dictionary initialized from a mapping objects
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 namevalue pairs
161 in the keyword argument list. For example: dict(one1, two2)
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) xy
176 pass
177
178 def __lt__(self, y): # real signature unknown; restored from __doc__
179 x.__lt__(y) xy
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 View Code 注意 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 dictionary4 dict(mapping) - new dictionary initialized from a mapping objects5 (key, value) pairs6 dict(iterable) - new dictionary initialized as if via:7 d {}8 for k, v in iterable:9 d[k] v10 dict(**kwargs) - new dictionary initialized with the namevalue pairs11 in the keyword argument list. For example: dict(one1, two2)12 13 14 def clear(self): # real signature unknown; restored from __doc__15 清除内容 16 D.clear() - None. Remove all items from D. 17 pass18 19 def copy(self): # real signature unknown; restored from __doc__20 浅拷贝 21 D.copy() - a shallow copy of D 22 pass23 24 staticmethod # known case25 def fromkeys(S, vNone): # 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 pass31 32 def get(self, k, dNone): # 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 pass36 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 False41 42 def items(self): # real signature unknown; restored from __doc__43 所有项的列表形式 44 D.items() - list of Ds (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 pass51 52 def iterkeys(self): # real signature unknown; restored from __doc__53 key可迭代 54 D.iterkeys() - an iterator over the keys of D 55 pass56 57 def itervalues(self): # real signature unknown; restored from __doc__58 value可迭代 59 D.itervalues() - an iterator over the values of D 60 pass61 62 def keys(self): # real signature unknown; restored from __doc__63 所有的key列表 64 D.keys() - list of Ds keys 65 return []66 67 def pop(self, k, dNone): # 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 raised72 73 pass74 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 a79 2-tuple; but raise KeyError if D is empty.80 81 pass82 83 def setdefault(self, k, dNone): # 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 pass87 88 def update(self, ENone, **F): # known special case of dict.update89 更新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] v97 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 Ds 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 Ds 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 Ds keys
113 pass
114
115 def viewvalues(self): # real signature unknown; restored from __doc__
116 D.viewvalues() - an object providing a view on Ds 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) xy
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) xy
145 pass
146
147 def __gt__(self, y): # real signature unknown; restored from __doc__
148 x.__gt__(y) xy
149 pass
150
151 def __init__(self, seqNone, **kwargs): # known special case of dict.__init__
152
153 dict() - new empty dictionary
154 dict(mapping) - new dictionary initialized from a mapping objects
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 namevalue pairs
161 in the keyword argument list. For example: dict(one1, two2)
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) xy
176 pass
177
178 def __lt__(self, y): # real signature unknown; restored from __doc__
179 x.__lt__(y) xy
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 python2 1 class dict(object):2 3 dict() - new empty dictionary4 dict(mapping) - new dictionary initialized from a mapping objects5 (key, value) pairs6 dict(iterable) - new dictionary initialized as if via:7 d {}8 for k, v in iterable:9 d[k] v10 dict(**kwargs) - new dictionary initialized with the namevalue pairs11 in the keyword argument list. For example: dict(one1, two2)12 13 14 def clear(self): # real signature unknown; restored from __doc__15 清除内容 16 D.clear() - None. Remove all items from D. 17 pass18 19 def copy(self): # real signature unknown; restored from __doc__20 浅拷贝 21 D.copy() - a shallow copy of D 22 pass23 24 staticmethod # known case25 def fromkeys(S, vNone): # 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 pass31 32 def get(self, k, dNone): # 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 pass36 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 False41 42 def items(self): # real signature unknown; restored from __doc__43 所有项的列表形式 44 D.items() - list of Ds (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 pass51 52 def iterkeys(self): # real signature unknown; restored from __doc__53 key可迭代 54 D.iterkeys() - an iterator over the keys of D 55 pass56 57 def itervalues(self): # real signature unknown; restored from __doc__58 value可迭代 59 D.itervalues() - an iterator over the values of D 60 pass61 62 def keys(self): # real signature unknown; restored from __doc__63 所有的key列表 64 D.keys() - list of Ds keys 65 return []66 67 def pop(self, k, dNone): # 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 raised72 73 pass74 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 a79 2-tuple; but raise KeyError if D is empty.80 81 pass82 83 def setdefault(self, k, dNone): # 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 pass87 88 def update(self, ENone, **F): # known special case of dict.update89 更新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] v97 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 Ds 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 Ds 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 Ds keys
113 pass
114
115 def viewvalues(self): # real signature unknown; restored from __doc__
116 D.viewvalues() - an object providing a view on Ds 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) xy
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) xy
145 pass
146
147 def __gt__(self, y): # real signature unknown; restored from __doc__
148 x.__gt__(y) xy
149 pass
150
151 def __init__(self, seqNone, **kwargs): # known special case of dict.__init__
152
153 dict() - new empty dictionary
154 dict(mapping) - new dictionary initialized from a mapping objects
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 namevalue pairs
161 in the keyword argument list. For example: dict(one1, two2)
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) xy
176 pass
177
178 def __lt__(self, y): # real signature unknown; restored from __doc__
179 x.__lt__(y) xy
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 python3 9、元组 元组其实跟列表差不多也是存一组数只不是它一旦创建便不能再修改所以又叫只读列表 语法 1 names (alex,jack,eric) 它只有2个方法一个是count,一个是index完毕。 程序练习 请闭眼写出以下程序。 程序购物车程序 需求: 启动程序后让用户输入工资然后打印商品列表允许用户根据商品编号购买商品用户选择商品后检测余额是否够够就直接扣款不够就提醒 可随时退出退出时打印已购买商品和余额 1 #!/usr/bin/env/python2 import sys,os,getpass3 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_choiceint(user_choice)#把数字转换成整型
22 if user_choice len(product_list) and user_choice0:#如果选择的数字编号小于产品列表的长度并且用户的选择的数字编号大于或等于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 转载于:https://www.cnblogs.com/kml777/p/5737297.html