python如何自动创建列表_Python自动化 【第二篇】:Python基础-列表、元组、字典...

本节内容(章节内容与标题可能略有出入)

模块初识

.pyc文件介绍

数据类型初识

数据运算

列表、元组操作

字符串操作

字典操作

集合操作

字符编码与转码

一、模块初识

结合os和sys模块示例

1 importos,sys2 os.system(''.join(sys.argv[1:])) #把用户输入的参数当作一条命令交给os.system执行

View Code

二、.pyc文件介绍

c是compiled的缩写。

其实Python和Java/C#一样,也是一门基于虚拟机的语言,我们先来了解一下Python程序的运行过程吧。

当我们在命令行中输入python hello.py时,其实是激活了Python的“解释器”,告诉“解释器”:你要开始工作了。可是在“解释”之前,其实执行的第一项工作和Java一样,是编译。其实Python也一样,当我们执行python hello.py时,他也一样执行了这么一个过程,所以我们应该这样来描述Python,Python是一门先编译后解释的语言。

简述python的运行过程

我们先来说两个概念,PyCodeObject和pyc文件。我们看到的pyc自然不必多说,而其实PyCodeObject则是Python编译器真正编译成的结果。当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中。当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则就重复上面的过程。

所以我们应该这样来定位PyCodeObject和pyc文件,我们说pyc文件其实是PyCodeObject的一种持久化保存方式。

三、数据类型初识

1、数字

int(整型)

在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~

自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。

浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。

2、布尔值

真或假

1 或 0

四、数据运算

算数运算:

比较运算:

赋值运算:

逻辑运算:

成员运算:

身份运算:

位运算:

五、再述数据类型

1.     列表、元祖操作

列表:列表是我们以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作。

定义列表

names = ['Tom',"Jack",'Rose']

通过下标访问列表中的元素,下标从0开始计数

1 >>>names[0]2

3 'Tom'

4

5 >>> names[2]6

7 'Rose'

8

9 >>> names[-1]10

11 'Rose'

12

13 >>> names[-2] #还可以倒着取

14

15 'Jack'

View Code

切片:取多个元素

1 >>> names = ['Tom','Jack','Rose','Lucy','Lilei','Green']2

3 >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4

4

5 ['Jack', 'Rose', 'Lucy']6

7 >>> names[1:-1] #取下标1至-1的值,不包括-1

8

9 ['Jack', 'Rose', 'Lucy', 'Lilei']10

11 >>> names[0:3]12

13 ['Tom', 'Jack', 'Rose']14

15 >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样

16

17 ['Tom', 'Jack', 'Rose']18

19 >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写

20

21 ['Lucy', 'Lilei', 'Green']22

23 >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个

24

25 ['Tom', 'Rose', 'Lilei']26

27 >>> names[::2] #和上句效果一样

28

29 ['Tom', 'Rose', 'Lilei']

View Code

追加

1 >>> names = ['Tom','Jack','Rose','Lucy','Lilei','Green']2

3 >>>names.append(“NEW”)4

5 >>>names6

7 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', 'NEW']

View Code

插入

1 >>>names2

3 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', 'NEW']4

5 >>>names.insert(2,"从Jack后面插入")6 >>>names7

8 ['Tom', 'Jack', '从Jack后面插入', 'Rose', 'Lucy', 'Lilei', 'Green', 'NEW']9

10 >>>names.insert(7,"再从Green后面插入")11 >>>names12

13 ['Tom', 'Jack', '从Jack后面插入', 'Rose', 'Lucy', 'Lilei', 'Green', '再从Green后面插入', 'NEW']

View Code

修改

1 >>>names2

3 ['Tom', 'Jack', '从Jack后面插入', 'Rose', 'Lucy', 'Lilei', 'Green', '再从Green后面插入', 'NEW']4

5 >>> names[2] = "该换人了"

6

7 >>>names8

9 ['Tom', 'Jack', '该换人了', 'Rose', 'Lucy', 'Lilei', 'Green', '再从Green后面插入', 'NEW']

View Code

删除

1 >>> del names[2]2

3 >>>names4

5 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', '再从Green后面插入', 'NEW']6

7 >>> names.remove(""再从Green后面插入"") #删除指定元素

8

9 >>>names10

11 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', 'NEW']12

13 >>> names.pop() #删除列表最后一个值

14

15 ‘NEW’16

17 >>>names18

19 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green']

View Code

扩展

1 >>>names2 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']3 >>> b = [1,2,3]4 >>>names.extend(b)5 >>>names6 ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]

View Code

拷贝

1 >>>names2

3 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', 1, 2, 3]4

5 >>> name_copy =names.copy()6

7 >>>name_copy8

9 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', 1, 2, 3]

View Code

上面这种copy叫浅copy,浅copy只copy了一层列表的元素,列表中如果再有列表的话,copy前后的两个列表的内层列表指向的是同一个内存地址,即将names的Rose改成 乔丹 后,names_copy的Rose也跟着改了。浅copy主要是为了节省内存空间。

再来看看深copy

1 importcopy2

3 names = ['Tom','Jack',['Rose','James'],'Lucy','Lilei','Green']4

5 names_copy =copy.deepcopy(names)6

7 print(names)8

9 print(names_copy)10

11 names[1] = "苍老师"

12

13 names[2][0] = "乔丹"

14

15 print(names)16

17 print(names_copy)

View Code

程序输出:

1 ['Tom', 'Jack', ['Rose', 'James'], 'Lucy', 'Lilei', 'Green']2

3 ['Tom', 'Jack', ['Rose', 'James'], 'Lucy', 'Lilei', 'Green']4

5 ['Tom', '苍老师', ['乔丹', 'James'], 'Lucy', 'Lilei', 'Green']6

7 ['Tom', 'Jack', ['Rose', 'James'], 'Lucy', 'Lilei', 'Green']

View Code

看出区别了吧,深copy是将内层列表也copy了,深copy在创建联合账号时可以用到。

统计

1 >>>names = ['Tom','Jack','Rose','Tom','Lucy','Tom','Lilei','Green']2 >>>names.count("Tom")

View Code

排序&翻转

1 >>> names = ['Tom','Jack','Rose','Lucy','Lilei','Green',1,2,3]2

3 >>> names.sort() #排序

4

5 Traceback (most recent call last):6

7 File "", line 1, in

8

9 TypeError: unorderable types: int() < str() #3.0里不同数据类型不能放在一起排序了,擦

10

11 >>> names[-3] = '1'

12

13 >>> names[-2] = '2'

14

15 >>> names[-1] = '3'

16

17 >>>names18

19 ['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', '1', '2', '3']20

21 >>>names.sort()22

23 >>>names24

25 ['1', '2', '3', 'Green', 'Jack', 'Lilei', 'Lucy', 'Rose', 'Tom']26

27 >>>names.reverse()28

29 ['3', '2', '1', 'Green', 'Lilei', 'Lucy', 'Rose', 'Jack', 'Tom']

View Code

获取下标

1 >>>names = ['Tom','Jack','Rose','Lucy','Lilei','Green',1,2,3]2 >>>names.index("Jack")

View Code

元组

元组:元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表。

1 names = ("tom","jack","rose")

它只有2个方法,一个是count,一个是index,完毕。

怎么样理解元组是不可改变的?

元组是不可改变是指,创建了之后,不能增加、删除、修改元祖中的元素,作为比较,列表可以增加(append),删除(remove),修改(list[0] = value),元祖则不能进行这些操作,需要注意的是,元祖不能修改,不代表元祖中的元素不能被修改,比如元祖t = ([1,2,3],4), t[0]是一个列表,可以修改,如t[0].append(5),之后t变成([1,2,3,5],4),过程中,t[0]指向同一个列表(id(t[0])没改变,但是列表的内容变了)

2.    字符串操作

a.count() #判断某元素在字符串中的个数

1 >>>a =‘abacdaefg’2 >>>a.count(‘a’)

a.capitalize() #把字符串首字母变为大写

1 >>>a =‘abacdaefg’2

3 >>>a. capitalize ()4

5 ‘Abacdaefg’

a.casefold() #将字母改成小写;汉语 & 英语环境下面继续用 lower()没问题;要处理其它语言(如德语)且存在大小写情况的时候再用casefold()。

1 >>>a = "this is A testing"

2

3 >>>a.casefold()4

5 this isa testing6 a.center() #7

8 a = "this is A testing"

9 print(a.center(40,"-"))10

11 -----------this is A testing------------

12 a.encode() #默认是UTF-8格式

13

14 msg = "好好学习,天天向上"

15 #print(msg.encode().decode(encoding='utf-8'))

16 print(msg.encode())17 print(msg.encode().decode())18

19 b'\xe5\xa5\xbd\xe5\xa5\xbd\xe5\xad\xa6\xe4\xb9\xa0\xef\xbc\x8c\xe5\xa4\xa9\xe5\xa4\xa9\xe5\x90\x91\xe4\xb8\x8a'#编码

20

21 好好学习,天天向上 #解码

View Code

查看了文档,是这么说明的:“Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter '�' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to '�'; casefold() converts it to "ss"

casefold更具有攻击性,例如德国的小写字母'口'相当于'ss' ,因为他已经小写了,所有lower不会做什么,但是Casefold会将它变为'ss' 似乎有些懂了。

a.endswith() #判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型;

#a.startswith() 判断是不是以参数中内容开头

1 a = "this is A testing"

2

3 print(a.endswith("ing"))4

5 True

a.expandtabs() #把字符串中的 tab 符号('\t')转为空格,返回字符串中的 tab 符号('\t')转为空格后生成的新字符串

1 a = "---\tthis is A testing"

2 print(a)3 print(a.expandtabs())4

5 --- this isA testing6

7 --- this is A testing

View Code

a.format() #格式化字符串

1 a = "this is A testing"

2 print("----->{test}".format(test=a))

a.format_map() #传入的参数是字典;无法循环传入字典里的所有参数

1 people ={2 'name':['zhang','ci'],3 'age':[55,33]4 }5

6 print(people)7

8 print('my name is {name[0]},my age is {age[0]}'.format_map(people))9 print('my name is {name[0]},my age is {age[1]}'.format_map(people))10 print('my name is {name[1]},my age is {age[0]}'.format_map(people))11 print('my name is {name[1]},my age is {age[1]}'.format_map(people))12

13 结果:14 {'name': ['zhang', 'ci'], 'age': [55, 33]}15 my name is zhang,my age is 55

16 my name is zhang,my age is 33

17 my name is ci,my age is 55

18 my name is ci,my age is 33

View Code

实现遍历字典数据并输出

1 people ={2 'name':['zhang','ci'],3 'age':[55,33]4 }5

6 print(['my name is {},my age is {}'.format(*x) for x in zip(people['name'],people['age'])])7 print(['my name is {},my age is {}'.format(*x) for x in zip(*map(people.get,['name','age']))])8

9

10 结果:11 ['my name is zhang,my age is 55', 'my name is ci,my age is 33']12 ['my name is zhang,my age is 55', 'my name is ci,my age is 33']

View Code

a.index()#同find()方法

1 a = 'fdsafdsf'

2 print(a.index('f'))3 print(a.index('d'))4 print(a.index('a'))5

6 结果:7 08 1

9 3

a.isalnum() #检测字符串是否由字母和数字组成

1 a = 'fdsafdsf'

2 b = 'fda34'

3 c = 'fdwer$#'

4 d = ' '

5 print(a.isalnum())6 print(b.isalnum())7 print(c.isalnum())8 print(d.isalnum())9

10 结果:11 True12 True13 False14 False

View Code

a.isalpha() #检测字符串是否只由字母组成

1 a = 'fdsafdsf'

2 b = 'fda34'

3 c = 'fdwer$#'

4 d = ' '

5 print(a.isalpha())6 print(b.isalpha())7 print(c.isalpha())8 print(d.isalpha())9

10

11 结果:12 True13 False14 False15 False

View Code

a.isdigit() #判断字符串是不是数字

1 a = 'fdsafdsf'

2 b = 'fda34'

3 c = 'fdwer$#'

4 d = ' '

5 e = '123213'

6 print(a.isdigit())7 print(b.isdigit())8 print(c.isdigit())9 print(d.isdigit())10 print(e.isdigit())11

12

13 结果:14 False15 False16 False17 False18 True

View Code

a.isidentifier() #判断字符串是否是合法的标识符

1 a = 'fdsafdsf'

2 b = 'fda34'

3 c = 'fdwer$#'

4 d = ' '

5 e = '123213'

6 f = '_4312'

7 print(a.isidentifier())8 print(b.isidentifier())9 print(c.isidentifier())10 print(d.isidentifier())11 print(e.isidentifier())12 print(f.isidentifier())13

14

15 结果:16 True17 True18 False19 False20 False21 True

View Code

a.islower() #判断是不是小写

#a.isupper() ,判断是不是大写

1 a = 'fdsEWREWfdsf'

2 b = '44#fda34'

3 c = 'fder$#'

4 d = ' '

5 e = '123214d3'

6 f = '_4312'

7 print(a.islower())8 print(b.islower())9 print(c.islower())10 print(d.islower())11 print(e.islower())12 print(f.islower())13

14

15 结果:16 False17 True18 True19 False20 True21 False22

23 结论:只要字符串中包含小写同时不包含大写即可,包含特殊字符也没事。

View Code

a.isnumeric() #检测字符串是否只由数字组成

1 a = 'fdsEWREWfdsf'

2 b = '44#fda34'

3 c = 'fder$#'

4 d = ' '

5 e = '1232143'

6 f = '_4312'

7 print(a.isnumeric())8 print(b.isnumeric())9 print(c.isnumeric())10 print(d.isnumeric())11 print(e.isnumeric())12 print(f.isnumeric())13

14 结果:15 False16 False17 False18 False19 True20 False

View Code

Python3.X里面,s.isdigit和s.isnumeric有什么区别?

1 num = "1" #unicode

2 num.isdigit() #True

3 num.isdecimal() #True

4 num.isnumeric() #True

5

6 num = "1" #全角

7 num.isdigit() #True

8 num.isdecimal() #True

9 num.isnumeric() #True

10

11 num = b"1" #byte

12 num.isdigit() #True

13 num.isdecimal() #AttributeError 'bytes' object has no attribute 'isdecimal'

14 num.isnumeric() #AttributeError 'bytes' object has no attribute 'isnumeric'

15

16 num = "IV" #罗马数字

17 num.isdigit() #True

18 num.isdecimal() #False

19 num.isnumeric() #True

20

21 num = "四" #汉字

22 num.isdigit() #False

23 num.isdecimal() #False

24 num.isnumeric() #True

25

26 ===================

27 isdigit()28 True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字29 False: 汉字数字30 Error: 无31

32 isdecimal()33 True: Unicode数字,,全角数字(双字节)34 False: 罗马数字,汉字数字35 Error: byte数字(单字节)36

37 isnumeric()38 True: Unicode数字,全角数字(双字节),罗马数字,汉字数字39 False: 无40 Error: byte数字(单字节)41

42 ================

43 importunicodedata44

45 unicodedata.digit("2") #2

46 unicodedata.decimal("2") #2

47 unicodedata.numeric("2") #2.0

48

49 unicodedata.digit("2") #2

50 unicodedata.decimal("2") #2

51 unicodedata.numeric("2") #2.0

52

53 unicodedata.digit(b"3") #TypeError: must be str, not bytes

54 unicodedata.decimal(b"3") #TypeError: must be str, not bytes

55 unicodedata.numeric(b"3") #TypeError: must be str, not bytes

56

57 unicodedata.digit("Ⅷ") #ValueError: not a digit

58 unicodedata.decimal("Ⅷ") #ValueError: not a decimal

59 unicodedata.numeric("Ⅷ") #8.0

60

61 unicodedata.digit("四") #ValueError: not a digit

62 unicodedata.decimal("四") #ValueError: not a decimal

63 unicodedata.numeric("四") #4.0

View Code

a.isspace() #判断字符串是否仅包含空格或制表符。注意:空格字符与空白是不同的

1 a = ' '

2 b = 'a b c'

3 c = '#$_ ds'

4 print(a.isspace())5 print(b.isspace())6 print(c.isspace())7

8

9 结果:10 True11 False12 False

View Code

a.istitle() #判断字符串是不是标题格式;检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

1 a = 'Dsdasd$sa'

2 b = 'Dsdasdsa'

3 c = '#$_ ds'

4 print(a.istitle())5 print(b.istitle())6 print(c.istitle())7

8

9 结果:10 False11 True12 False

View Code

a.join() #连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串

1 b = 'Dsdas$$$dsa'

2 c = '#$_ ds'

3 d = ['1','2','3','4']4

5 print('_'.join(b))6 print('_'.join(c))7 print('_'.join(d))8

9

10 结果:11 D_s_d_a_s_$_$_$_d_s_a12 #_$___ _d_s_

13 1_2_3_4

View Code

ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。a.rjust() ,返回一个原字符串右对齐,并使用空格填充至指定长度的新字符串

1 str = "this is string example....wow!!!";2

3 print str.ljust(50, '0');4

5

6 结果:7 this is string example....wow!!!000000000000000000

View Code

a.lower() #把大写转成小写;a.swapcase(),对字符串的大小写字母进行转换

1 b = 'Dsdas$$$dsa'

2 print(b.lower())3

4

5 结果:6 dsdas$$$dsa

a.lstrip() #去掉字符串左边的空格;a.rstrip(),去掉字符串右边的空格;a.strip(),去掉字符串左右边界的空格,字符串中间的空格不处理。

1 1 b = 'Dsda s$$$dsa'

2 2 print(b.lstrip())3 3 print(b.rstrip())4 4 print(b.strip())5 5

6 6

7 7结果:8 8Dsda s$$$dsa9 9Dsda s$$$dsa10 10 Dsda s$$$dsa

View Code

maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

1 以下实例展示了使用maketrans() 方法将所有元音字母转换为指定的数字:2

3

4 from string import maketrans #必须调用 maketrans 函数。

5

6 intab = "aeiou"

7 outtab = "12345"

8 trantab =maketrans(intab, outtab)9

10 str = "this is string example....wow!!!";11 print(str.translate(trantab))12

13

14 结果:15 th3s 3s str3ng 2x1mpl2....w4w!!!

View Code

a.replace() #把字符串中的 old(旧字符串) 替换成 new(新字符串)

1 b = 'Dsda s$$$dsa'

2

3 print(b.replace('Dsda', 'anqing'))4

5

6 结果:7 anqing s$$$dsa

View Code

a.rfind() #返回字符串最后一次出现的位置,如果没有匹配项则返回-1

a.rindex() #返回子字符串 str 在字符串中最后出现的位置

1 b = 'Dsda s$$$dsa'

2 print(b.rfind('dsa'))3 print(b.rindex('Dsda'))4

5

6 结果:7 19

8 7

View Code

a.title() #把字符串转成标题格式

1 a = "MY NAME Is TOM"

2

3 print(a.title())4

5 My Name Is Tom

View Code

a.translate() # 根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中

1 把aeiou对应替换成12345:2

3

4 from string import maketrans #引用 maketrans 函数。

5

6 intab = "aeiou"

7 outtab = "12345"

8 trantab =maketrans(intab, outtab)9

10 str = "this is string example....wow!!!";11 printstr.translate(trantab);12

13 结果:14 th3s 3s str3ng 2x1mpl2....w4w!!!15

16

17 去除字符串中的 'x' 和 'm'字符:18

19

20

21 from string import maketrans #Required to call maketrans function.

22

23 intab = "aeiou"

24 outtab = "12345"

25 trantab =maketrans(intab, outtab)26

27 str = "this is string example....wow!!!";28 print str.translate(trantab, 'xm');29

30 结果:31 th3s 3s str3ng 21pl2....w4w!!!

View Code

六、字典操作

字典的特性:

·dict是无序的

·key必须是唯一的, 天生去重

增加

1 >>> info["stu04"] = "苍老师"

2 >>>info3 {'stu04': '苍老师', 'stu01': 'Tom', 'stu02': 'Jack', 'stu03': 'Rose'}

删除

1 >>>info2

3 {'stu01': 'Tom', 'stu03': 'Rose', 'stu04': 'Lilei', 'stu02': 'Jack'}4

5 >>>info.pop(‘stu02’) #标准删除

6

7 >>>info8

9 {'stu01': 'Tom', 'stu04': 'Lilei', 'stu03': 'Rose'}10

11 >>>del info['stu01'] #另外一种删除方式

12

13 >>>info14

15 {'stu02': 'Jack', 'stu03': 'Rose', 'stu04': 'Lilei'}16

17 >>> info.popitem() #随机删除

View Code

修改

1 >>> info['stu01'] = "Lily"

2

3 >>>info4

5 {'stu02': 'Jack', 'stu01': 'Lily', 'stu04': '苍老师', 'stu03': 'Rose'}

查找

1 >>> info = {'stu02': 'Tom', 'stu03': 'Jack'}2

3 >>>

4

5 >>> "stu02" in info #标准用法

6

7 True8

9 >>> info.get("stu02") #获取

10

11 'Tom'

12

13 >>> info["stu02"] #同上,但是看下面

14

15 'Tom'

16

17 >>> info["stu05"] #如果一个key不存在,就报错,get不会,不存在只返回None

18

19 Traceback (most recent call last):20

21 File "", line 1, in

22

23 KeyError: 'stu05'

View Code

字典中可以嵌套字典、列表、元组

1 V ={2 'car':{3 'BMW':['X5','M3'],4 "BenZ":['GLK','S300'],5 "Audi":['A8','Q7'],6 },7 'motorcycle':{8 "川崎":["很贵","好看"],9 "庞巴迪":["也很贵","霸气"]10 },11 'bike':{12 "捷安特":["不错","台湾产"],13 "永久":["便宜","国产"]14 }15 }16

17 V['car']['BMW'][1] += ":$500"

18

19 print(V['car']['BMW'][1])20

21 M3:$500

View Code

#values

1 >>>info.values()2

3 dict_values(['Jack', 'Tom', 'Rose', 'Lilei'])

#keys

1 >>>info.keys()2

3 dict_keys(['stu01', 'stu03', 'stu04', 'stu02'])

#setdefault

1 >>>info.setdefault('stu05','Lily')2

3 ‘Lily’4

5 >>>info6

7 {'stu01': 'Tom', 'stu02': 'Jack', 'stu04': 'Lilei', 'stu03': 'Rose', 'stu05': 'Lily'}8

9

10

11 >>> info.setdefault('stu02','fengjie') #已经存在的value不会被setdefault改变

12

13 ‘jack’14

15 >>>info16

17 {'stu05': 'Lily', 'stu03': 'Rose', 'stu02': 'Jack', 'stu04': 'Lilei', 'stu01': 'Tom'}

View Code

#update,不存在的k-v直接加上,存在的k-v则更新其value。

1 >>>info2

3 {'stu03': 'Rose', 'stu01': 'Tom', 'stu02': 'Jack', 'stu04': 'Lilei'}4

5 >>> b = {1: 2, 3: 4, 'stu02': '苍老师'}6

7 >>>info.update(b)8

9 >>>info10

11 {'stu03': 'Rose', 3: 4, 'stu02': '苍老师', 1: 2, 'stu04': 'Lilei', 'stu01': 'Tom'}

View Code

#items

1 info.items() #以列表返回可遍历的(键, 值) 元组数组

2

3 dict_items([(1, 2), ('stu01', 'Tom'), (3, 4), ('stu02', '苍老师'), ('stu03', 'Rose'), ('stu04', 'Lilei')])

循环dict

1 for key ininfo:2

3 print(key,info[key])

七、字符编码与转换

1 msg = "好好学习,天天向上"

2 print(msg.encode('utf-8'))3 print(msg.encode('utf-8').decode('utf-8'))4

5 程序输出:6

7 b'\xe5\xa5\xbd\xe5\xa5\xbd\xe5\xad\xa6\xe4\xb9\xa0\xef\xbc\x8c\xe5\xa4\xa9\xe5\xa4\xa9\xe5\x90\x91\xe4\xb8\x8a'

8 好好学习,天天向上

View Code

八、集合操作

集合是一个无序的,不重复的数据组合,它的主要作用如下:

去重,把一个列表变成集合,就自动去重了

关系测试,测试两组数据之前的交集、差集、并集等关系

常用操作

1 s = set([3,5,9,10]) #创建一个数值集合

2

3 t = set("Hello") #创建一个唯一字符的集合

4

5

6 a = t | s #t 和 s的并集

7

8 b = t & s #t 和 s的交集

9

10 c = t – s #求差集(项在t中,但不在s中)

11

12 d = t ^ s #对称差集(项在t或s中,但不会同时出现在二者中)

13

14

15

16 基本操作:17

18 t.add('x') #添加一项

19

20 s.update([10,37,42]) #在s中添加多项

21

22

23

24 使用remove()可以删除一项:25

26 t.remove('H')27

28

29 len(s)30 set 的长度31

32 x ins33 测试 x 是否是 s 的成员34

35 x not ins36 测试 x 是否不是 s 的成员37

38 s.issubset(t)39 s <=t40 测试是否 s 中的每一个元素都在 t 中41

42 s.issuperset(t)43 s >=t44 测试是否 t 中的每一个元素都在 s 中45

46 s.union(t)47 s |t48 返回一个新的 set 包含 s 和 t 中的每一个元素49

50 s.intersection(t)51 s &t52 返回一个新的 set 包含 s 和 t 中的公共元素53

54 s.difference(t)55 s -t56 返回一个新的 set 包含 s 中有但是 t 中没有的元素57

58 s.symmetric_difference(t)59 s ^t60 返回一个新的 set 包含 s 和 t 中不重复的元素61

62 s.copy()63 返回 set “s”的一个浅复制

View Code

九、文件的打开模式

打开文件的模式有:

r,只读模式(默认)。

w,只写模式。【不可读;不存在则创建;存在则删除内容;】

a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

r+,可读写文件。【可读;可写;可追加】

w+,写读

a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

rU

r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

rb

wb

ab

sort()和sorted()

names = ['Tom','Jack','Rose','Lucy','Lilei','Green','1','2','3']

sorted(names)#不会改变原序列

print(names)

names.sort()#直接作用到原序列

print('names:',names)print('sorted(names):',sorted(names))#结果:

['Tom', 'Jack', 'Rose', 'Lucy', 'Lilei', 'Green', '1', '2', '3']

names: ['1', '2', '3', 'Green', 'Jack', 'Lilei', 'Lucy', 'Rose', 'Tom']

sorted(names): ['1', '2', '3', 'Green', 'Jack', 'Lilei', 'Lucy', 'Rose', 'Tom']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值