第1章 深入学习Python数据类型

Python3中有六个标准的数据类型:

Number(数字)

String(字符串)

List(列表)

Tuple(元组)

Dictionary(字典)

Sets(集合)

一、数字类型(Number)

Python3支持的数字类型:int(整型)、float(浮点型)、complex(复数)

数字类型定义的时候变量名后面直接跟数字,数字类型是不可变数据类型。

整型与浮点型

1、int(整型)

定义方式:

age = 18 #age=int(18)

用途:

年龄、等级、身份证号、QQ号等

2、float(浮点型)

定义方式:

salary = 3.1 #salary = float(3.1)

用途:

薪资、身高、体重、体质参数等

数字类型的基本操作

#数字的操作类型主要在程序中起到一个判断作用

num1=b'4' #bytes

num2=u'4' #Unicode

num3='四' #中文数字

num4='Ⅳ' #罗马数字

#isdigit()#作用就是判断是否是数字

print(num1.isdigit()) #True

print(num2.isdigit()) #True

print(num3.isdigit()) #False

print(num4.isdigit()) #False

#isdecimal #bytes类型无isdecimal方法,uncicode有

print(num2.isdecimal()) #True

print(num3.isdecimal()) #False

print(num4.isdecimal()) #False

#isnumberic #bytes类型无isnumberic方法,unicode,中文数字,罗马数字有

print(num2.isnumeric()) #True

print(num3.isnumeric()) #True

print(num4.isnumeric()) #True

View Code

Python 还支持复数,复数由实数部分和虚数部分构成,可以用 a+bj,或者 complex(a,b) 表示,复数的实部 a 和 虚部 b 都是浮点型。

二、字符串(String)

定义字符串的时候需要用引号引起来,可以用单,双,三引号,三引号多表示多行字符串,这样就可以省掉“\n”换行符换行。字符串是不可变类型。

定义方式:

#单引号定义:

>>> msg = 'hello world'

>>> print(msg)

hello world#双引号定义:

>>> msg = "hello world"

>>> print(msg)

hello world#三引号定义:

msg='''hello,

my name is lionel wang,

how are you.'''

print(msg)

View Code

用途:

姓名、性别、住址等描述性数据

字符串常用操作

1、按索引取值(正向取+反向取),字符串只能取,不能改

>>> msg = 'hello world'

>>> print(msg[0])

h

>>> print(msg[-1])

d

2、切片(顾头不顾尾,步长)

>>> msg = 'hello world'

>>> print(msg[0:3])

hel>>> print(msg[0:7:2])

hlow>>> print(msg[5:1:-1])

oll>>> print(msg[-1:0:-1])

dlrow olle>>> print(msg[-1::-1])

dlrow olleh

View Code

3、长度len

>>> msg = 'hello world'

>>> print(msg.__len__())

11

>>> print(len(msg)) # msg.__len__()

11

4、成员运算in和not in

msg = 'hello world'

print('llo' inmsg)print('llo' not in msg)

5、删除空白(lstrip、rstrip、strip)

删除空白

6、字符串切分(split、rsplit)

split(seq=None, maxsplit=-1),不带参数默认是以空格为分隔符切片字符串,如果maxsplit参数有设置,则仅分隔maxsplit个字符串,返回切片后的子字符串拼接的列表。

#Linux系统passwd文件切分家目录

>>> path_info = 'root:x:0:0::/root:/bin/bash'

>>> print(path_info.split(':')[5])/root#Linux切割命令和参数

>>> cmd = 'get /root/a/b/c/d.txt'

>>> print(cmd.split())

['get', '/root/a/b/c/d.txt']#切割文件路径

>>> file_path= 'C:\\a\\d.txt'

>>> print(file_path.split('\\',1))

['C:', 'a\\d.txt']#rsplit从右往左切割

>>> file_path= 'C:\\a\\d.txt'

>>> print(file_path.rsplit('\\',1))

['C:\\a', 'd.txt']

View Code

7、循环

#打印字符串中所有字符

方法1:while循环

msg= 'hello world'size=len(msg)

n=0while n

n+= 1方法2:for循环

msg= 'hello world'

for i inmsg:print(i)

方法3:使用range函数

msg= 'hello world'

for i inrange(len(msg)):print(msg[i])

执行结果:

h

e

l

l

o

w

o

r

l

d

range函数介绍:

语法:range(start, stop[, step])

start:计数从start开始。默认是从0开始。例如:range(5)等价于range(0, 5)

stop:计数到stop结束,但不包括 stop。例如:range(0,5) 是[0, 1, 2, 3, 4]没有5

step:步长,默认为1。例如:range(0,5) 等价于range(0, 5, 1)

例子:for i in range(0,5,2):print(i)

执行结果:

02

4

View Code

8、修改字符串的大小写(title、upper、lower)

#string.title() 字符串首字母大写

>>> name = "lionel messi"

>>> print(name.title())

Lionel Messi#string.upper() 字符串全部大写

>>> name = "Lionel Messi"

>>> print(name.upper())

LIONEL MESSI#string.lower() 字符串全部小写

>>> name = "Lionel Messi"

>>> print(name.lower())

lionel messi

View Code

9、字符串拼接(“+”)

#Python使用加号(+)来合并字符串。

>>> first_name = "lionel"

>>> last_name = "messi"

>>> full_name = first_name + " " +last_name>>> print("Hello," + full_name.title() + "!")

Hello, Lionel Messi!#可以使用拼接来创建消息,再把整条消息存储在一个变量中。

>>> first_name = "lionel"

>>> last_name = "messi"

>>> full_name = first_name + " " +last_name>>> msg = "Hello," + full_name.title() + "!"

>>> print(msg)

Hello, Lionel Messi!

View Code

10、使用制表符或换行符来添加空白(\n\t)

在编程中,空白泛指任何非打印字符,如空格、制表符和换行符。使用空白来组织输出,使其更易读。

>>> print("\tpython")

python>>> print("Languages:\n\tPython\n\tC\n\tC++")

Languages:

Python

C

C++

View Code

11、字符串替换(replace)

#语法:string.replace(old, new[, count]) 字符串替换#把字符串中的old子字符串替换成new子字符串,如果count指定,则替换不超过count次。

>>> name = 'alex say: i have one tesla,my name is alex'

>>> print(name.replace('alex','SB',1))

SB say: i have one tesla,my nameis alex

View Code

12、字符串格式化(format())

format()方法接受位置参数和关键字参数,二者均传递到一个叫做replacement字段。而这个replacement字段在字符串内有大括号({})表示。

格式化输出的三种玩法:

#按顺序传值

>>> print('{} {} {}'.format('lionel',18,'male'))

lionel18male#按索引传值

>>> print('{1} {0} {1}'.format('lionel',18,'male'))#按key/value方式传值

18 lionel 18

>>> print('{name} {age} {sex}'.format(name = 'wangzhiwei',age = 18,sex = 'male'))

wangzhiwei18 male

View Code

字符串中{1}、{0}和{1}跟位置有关,依次被format()的三个参数替换,那么format()的三个参数叫做位置参数。{name}、{age}和{sex}就相当于三个标签,format()将参数中等值的字符串替换进去,这就是字符串的关键参数。

练习:

#如果要把大括号打印出来,只需要用多一层的大括号包起来即可。

>>> print('{{0}}'.format("不打印"))

{0}#格式化输出小数点

>>> print('{0}: {1:.2f}'.format("圆周率",3.1415926))

圆周率:3.14

#位置参数{1}跟平常不同,后边多了个冒号。在替换域中,冒号表示格式化符号的开始,“.2”的意思是四舍五入保留到两位小数点,而f的意思是浮点数,所以按照格式化符号的要求打印出了3.14。

View Code

13、格式化操作符%

例子:

>>> print('%c' %97)

a>>> print('%c%c%c' %(70,105,67))

FiC>>> print('%d转换八进制是: %o' %(123,123))

123转换八进制是:173

>>> print('%f用科学计数法表示是: %e' %(1520000000,1520000000))1520000000.000000用科学计数法表示是: 1.520000e+09

View Code

例子:

>>> '%5.1f' %21.345

'21.3'

>>> '%.2e' %21.345

'2.13e+01'

View Code

14、以...开头,以...结尾(startswith、endswith)

>>> msg = 'lionel is male'

>>> print(msg.startswith('lionel'))

True>>> print(msg.startswith('lio'))

True>>> print(msg.endswith('male'))

True

View Code

15、将序列中的元素以指定的字符连接生成一个新的字符串(join)

>>> info = 'root:x:0:0'

>>> l = info.split(':')>>> print(':'.join(l))

root:x:0:0

View Code

16、判断输入的字符串是否是数字(isdigit)

age = input('>>:').strip()ifage.isdigit():

age=int(age)else:print('必须输入数字')

View Code

17、其他了解

1、find、rfind、index、rindex、count

2、center、ljust、rjust、zfill

3、expandtabs

4、captalize、swapcase

5、is其他

#find,rfind,index,rindex,count

name='egon say hello'

print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引#print(name.index('e',2,4)) #同上,但是找不到会报错

print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有

#center,ljust,rjust,zfill

name='egon'

print(name.center(30,'-'))print(name.ljust(30,'*'))print(name.rjust(30,'*'))print(name.zfill(50)) #用0填充

#expandtabs

name='egon\thello'

print(name)print(name.expandtabs(1))#captalize,swapcase,title

print(name.capitalize()) #首字母大写

print(name.swapcase()) #大小写翻转

msg='egon say hi'

print(msg.title()) #每个单词的首字母大写

#is数字系列#在python3中

num1=b'4' #bytes

num2=u'4' #unicode,python3中无需加u就是unicode

num3='四' #中文数字

num4='Ⅳ' #罗马数字

#isdigt:bytes,unicode

print(num1.isdigit()) #True

print(num2.isdigit()) #True

print(num3.isdigit()) #False

print(num4.isdigit()) #False

#isdecimal:uncicode#bytes类型无isdecimal方法

print(num2.isdecimal()) #True

print(num3.isdecimal()) #False

print(num4.isdecimal()) #False

#isnumberic:unicode,中文数字,罗马数字#bytes类型无isnumberic方法

print(num2.isnumeric()) #True

print(num3.isnumeric()) #True

print(num4.isnumeric()) #True

#三者不能判断浮点数

num5='4.3'

print(num5.isdigit())print(num5.isdecimal())print(num5.isnumeric())'''总结:

最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景

如果要判断中文数字或罗马数字,则需要用到isnumeric'''

#is其他

print('===>')

name='egon123'

print(name.isalnum()) #字符串由字母或数字组成

print(name.isalpha()) #字符串只由字母组成

print(name.isidentifier())print(name.islower())print(name.isupper())print(name.isspace())print(name.istitle())

View Code

三、列表(List)

列表是由一系列按特定顺序排列的元素组成。可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。

在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。列表打印出来的还是列表。

定义方式:

“[]”内可以有多个任意类型的值,逗号分隔。

my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质my_girl_friends=list([...])

l=list('abc')

View Code

用途:

多个装备,多个爱好,多门课程等

列表常用操作

1、列表之通过索引访问列表元素

在Python中,第一个列表元素的索引为0,而不是1。

例子1:>>> my_friends = ['wang','lionel','messi',4,10,30]>>> print(my_friends[0])

wang

例子2:使用字符串title()方法打印列表元素>>> my_friends = ['wang','lionel','messi',4,10,30]>>> print(my_friends[0].title())

Wang

例子3:打印最后一个列表元素>>> my_friends = ['wang','lionel','messi',4,10,30]>>> print(my_friends[-1])30

#Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,可让Python返回最后一个列表元素。索引-2返回倒数第二个列表元素,索引-3返回倒数第三个列表元素,以此类推。

View Code

2、列表之列表增删改(append、extend、insert、pop、remove)

#1、append() 增加列表元素#例子1:

>>> my_friends = ['wang','lionel','messi',4,10,30]>>> my_friends.append('wangzhiwei')>>> print(my_friends)

['wang', 'lionel', 'messi', 4, 10, 30, 'wangzhiwei']#注意:append()方法会将增加的元素放在列表末尾。

#例子2:定义一个空列表,再使用append()方法添加元素。

>>> lists=[]>>> lists.append('a')>>> lists.append('b')>>> lists.append('c')>>> print(lists)

['a', 'b', 'c']#2、extend() 向列表末尾添加多个元素

>>> number = [1,2,3]>>> number.extend(4,5) #extend()方法事实上使用一个列表来扩展另一个列表。

Traceback (most recent call last):

File"", line 1, in TypeError: extend() takes exactly one argument (2given)>>> number.extend([4,5])>>> print(number)

[1, 2, 3, 4, 5]#注意:extend()方法事实上使用一个列表来扩展另一个列表,所以它的参数应该是一个列表。

#3、 insert() 向列表任意位置插入

insert()方法有两个参数:第一个参数代表在列表中的位置,第二个参数是在这个位置处插入一个元素。#例子:

>>> number = [1,2,3]>>> number.insert(1,0)>>> print(number)

[1, 0, 2, 3]#4、pop()按照索引删除元素

将元素从列表中删除,并接着使用它的值。在Web应用程序中,可能要将用户从活跃成员列表中删除,并将其加入到非活跃成员列表中。方法pop()可删除列表末尾的元素,并让你能够接着使用它。#例子1:

>>> my_friends = ['wang', 'lionel', 'messi']>>>my_friends.pop()>>> print(my_friends)

['wang', 'lionel']#注意:pop()方法默认删除列表末尾的元素。

#例子2:根据索引删除元素

>>> my_friends = ['wang', 'lionel', 'messi']>>>my_friends.pop(0)>>> print(my_friends)

['lionel', 'messi']#5、remove()根据值删除元素

remove()函数用于移除列表中某个值的第一个匹配项。该方法没有返回值但是会移除列表中的某个值的第一个匹配项。#例子:

>>> my_friends = ['wang', 'lionel', 'messi']>>> my_friends.remove('lionel')>>> print(my_friends)

['wang', 'messi']#6、根据索引修改列表中的元素

根据索引修改列表中的元素,也就是根据索引赋值。#例子:

>>> my_friends = ['wang', 'lionel', 'messi']>>> my_friends[1]='abc'

>>> print(my_friends)

['wang', 'abc', 'messi']

View Code

3、列表之切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。Python在到达你指定的第二个索引前面的元素后停止。要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为0、1和2的元素,第一个元素索引≥切片<最后一个元素索引。

#例子1:

>>> my_friends = ['wang', 'lionel', 'messi']>>> print(my_friends[0:2])

['wang', 'lionel']#例子2:如果没有指定第一个索引,Python将自动从列表开头开始

>>> my_friends = ['wang', 'lionel', 'messi']>>> print(my_friends[:2])

['wang', 'lionel']#例子3:如果没有指定最后一个索引,Python将自动提取从第一个元素索引到列表末尾的所有元素

>>> my_friends = ['wang', 'lionel', 'messi']>>> print(my_friends[1:])

['lionel', 'messi']#例子4:负数索引返回离列表末尾相应距离的元素,因此可以输出列表末尾的任何切片。

>>> my_friends = ['wang', 'lionel', 'messi']>>> print(my_friends[-2:])

['lionel', 'messi']

View Code

4、列表之统计列表长度(len()和__len__())

#例子1:

>>> my_friends = ['wang', 'lionel', 'messi']>>> print(len(my_friends))3

#例子2:

>>> my_friends = ['wang', 'lionel', 'messi']>>> print(my_friends.__len__())3

View Code

5、列表之in(包含)和not in(不包含)符号判断

在python中可以使用in符号判断指定的元素是否存在于列表中,返回值为布尔类型。

#例子1:

>>> my_friends = ['wang', 'lionel', 'messi']>>> print('asd' inmy_friends)

False>>> print('asd' not inmy_friends)

True#例子2:

>>> msg = 'my name is wangzhiwei'

>>> print('wangzhiwei' inmsg)

True

View Code

6、清空列表(clear)

clear()方法用于清空(或删除)列表中的所有数据项。

#例子:

>>> my_friends = ['wang', 'lionel', 'messi']>>>my_friends.clear()>>> print(my_friends)

[]

View Code

7、拷贝列表(copy)

copy()方法用于复制列表。

#例子:

>>> my_friends = ['wang', 'lionel', 'messi']>>> list =my_friends.copy()>>> print(list)

['wang', 'lionel', 'messi']

View Code

8、统计元素在列表中出现的次数(count)

#例子:

>>> my_friends = ['wang', 'lionel', 'messi','wang']>>> print(my_friends.count('wang'))2

View Code

9、从列表中找出某个值第一个匹配项的索引位置(index)

index()方法用于从列表中找出某个值第一个匹配项的索引位置。

#例子:

>>> my_friends = ['wang', 'lionel', 'messi','wang']>>> print(my_friends.index('wang'))

0

View Code

10、反向列表中元素(reverse)

#reverse()方法用于反向列表中元素。#例子:

>>> my_friends = ['wang', 'lionel', 'messi','wang']>>>my_friends.reverse()>>> print(my_friends)

['wang', 'messi', 'lionel', 'wang']

View Code

11、对原列表进行排序(sort)

sort()方法用于对原列表进行排序,默认从小到大排序。

#例子1:对原列表进行排序(从小到大)

>>> list = [2,3,1,-1]>>>list.sort()>>> print(list)

[-1, 1, 2, 3]#例子2:对原列表进行排序(从大到小)

>>> list = [2,3,1,-1]>>> list.sort(reverse=True)>>> print(list)

[3, 2, 1, -1]

View Code

12、解压序列 * 的妙用

#例子:打印第一个元素和最后一个元素

>>> data=['lionel',23,[2018,12,14]]>>> a,*_,b =data>>> print(a,b)

lionel [2018, 12, 14]

View Code

13、列表模拟队列

#练习1:模拟队列:先进先出#方法1:

fifo =[]#入队

fifo.append('first')

fifo.append('second')

fifo.append('third')print(fifo)#出队

print(fifo.pop(0))print(fifo.pop(0))print(fifo.pop(0))

执行结果:

['first', 'second', 'third']

first

second

third#方法2:

fifo =[]#入队

fifo.insert(0,'first')

fifo.insert(0,'second')

fifo.insert(0,'third')print(fifo)#出队

print(fifo.pop())print(fifo.pop())print(fifo.pop())

执行结果:

['third', 'second', 'first']

first

second

third#练习2:模拟堆栈:先进后出#方法1:

lifo =[]#入队

lifo.insert(0,'first')

lifo.insert(0,'second')

lifo.insert(0,'third')print(lifo)#出队

print(lifo.pop(0))print(lifo.pop(0))print(lifo.pop(0))

执行结果:

['first', 'second', 'third']

third

second

first#方法2:

lifo =[]#入队

lifo.append('first')

lifo.append('second')

lifo.append('third')print(lifo)#出队

print(lifo.pop())print(lifo.pop())print(lifo.pop())

执行结果:

['first', 'second', 'third']

third

second

first

View Code

四、元组(Tuple)

Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组 。

定义方式:

与列表类型比,只不过“[]”换成“()”。

age = (11,22,33,44,55) #本质age=tuple((11,22,33,44,55))

View Code

用途:

存多个值,对比列表来说,元组不可变(是可以当做字典的key),只用是用来读

元组常用操作

1、按索引取值(正向取+反向取):只能取按索引取值(正向取+反向取):只能取

age = (11,22,33,44,55)print(age[0])print(age[-1])

执行结果:11

55

View Code

2、切片(顾头不顾尾)

age = (11,22,33,44,55)print(age[0:3])print(age[2:])print(age[:2])

执行结果:

(11, 22, 33)

(33, 44, 55)

(11, 22)

View Code

3、统计元组长度(len)

age = (11,22,33,44,55)print(len(age))

执行结果:5

View Code

4、元组的成员运算(in和not in)

age = (11,22,33,44,55)print(22 inage)

执行结果:

True

View Code

5、遍历元组

age = (11,22,33,44,55)for item inage:print(item)

执行结果:11

22

33

44

55

View Code

6、从元组中找出某个值第一个匹配项的索引位置(index)

age = (11,22,44,33,55,33)print(age.index(33))

执行结果:3

View Code

7、统计元素在元组中出现的次数(count)

age = (11,22,44,33,55,33)print(age.count(33))

执行结果:2

View Code

五、字典(Dictionary)

在Python中,字典是一系列键值对(key/value) 。每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值,但是键必须是不可变类型(int、float、str、tuple)。

定义方式:

key必须是不可变类型(int,float,str,tuple),value可以是任意类型。

info = {'name':'lionel','age':18,'sex':'male'} #info=dict({'name':'lionel','age':18,'sex':'male'})

info=dict(name='lionel',age=18,sex='male')

info=dict([['name','lionel'],('age',18)])

{}.fromkeys(('name','age','sex'),None)

View Code

用途:

存放多个值,key:value,存取速度快。

字典常用操作

1、按key存取值:可存可取

#通过key取值

d = {'name':'lionel'}print(d['name'])

执行结果:

lionel#添加字典

d['age']=18

print(d)

执行结果:

{'name': 'lionel', 'age': 18}

View Code

2、统计字典长度(len)

info = {'name':'lionel','age':18,'sex':'male'}print(len(info))

执行结果:3

View Code

3、字典的成员运算(in和not in)

info = {'name':'lionel','age':18,'sex':'male'}print(len(info))

执行结果:3

View Code

4、字典的删除(pop、popitem)

pop()方法删除字典给定键key所对应的值,返回值为被删除的值。

popitem()方法随机返回并删除字典中的一对键和值(一般删除末尾对)。如果字典已经为空,却调用了此方法,就报出KeyError异常。

#pop()方法

info = {'name':'lionel','age':18,'sex':'male'}print(info.pop('name'))print(info)#popitem()方法

print(info.popitem())print(info)

执行结果:

lionel

{'age': 18, 'sex': 'male'}

('sex', 'male')

{'age': 18}

View Code

5、键keys(),值values(),键值对items()

key()用于返回字典中的键,values()用于返回字典中所有的值,item()返回字典中所有的键值对。

#key()方法

info = {'name':'lionel','age':18,'sex':'male'}print(info.keys())#将结果转化为列表

print(list(info.keys()))

执行结果:

dict_keys(['name', 'age', 'sex'])

['name', 'age', 'sex']#values()方法

info = {'name':'lionel','age':18,'sex':'male'}print(info.values())#将结果转化为列表

print(list(info.values()))

执行结果:

dict_values(['lionel', 18, 'male'])

['lionel', 18, 'male']#item()方法

info = {'name':'lionel','age':18,'sex':'male'}print(info.items())#将结果转化为列表

print(list(info.items()))

执行结果:

dict_items([('name', 'lionel'), ('age', 18), ('sex', 'male')])

[('name', 'lionel'), ('age', 18), ('sex', 'male')]

View Code

6、遍历字典

info = {'name':'lionel','age':18,'sex':'male'}for k ininfo:print(k,info[k])

View Code

7、get()方法使用

get()函数返回指定键的值,如果值不在字典中返回默认值(None)。

info = {'name':'lionel','age':18,'sex':'male'}print(info.get('hobbies'))print(info.get('hobbies','没有这个key'))print(info.pop('name1','None'))

执行结果:

None

没有这个key

None

View Code

8、更新字典(update)

update()函数把字典dict2的键/值对更新到dict1里。如果key存在,则修改对应value;如果key不存在,则插入。

info = {'name':'lionel','age':18,'sex':'male'}

d= {'x':1,'y':2,'name':'LIONEL'}

info.update(d)print(info)

执行结果:

{'name': 'LIONEL', 'age': 18, 'sex': 'male', 'x': 1, 'y': 2}

View Code

9、setdefault()方法使用

setdefault()方法和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。如果key存在,则不修改,返回已经有的key对应的value;如果key不存在就插入。

info = {'name':'lionel','age':16,'sex':'male'}

value=info.setdefault('age',18) #如果key存在,则不修改,返回已经有的key对应的value;如果key不存在就插入

print(value)print(info)

执行结果:16{'name': 'lionel', 'age': 16, 'sex': 'male'}

View Code

setdefault()用法升级版:

info={'name':'lionel','hobbies':['music']}

hobbies_list=info.setdefault('hobbies',[])print(hobbies_list)

hobbies_list.append('play')

hobbies_list.append('read')print(info)

执行结果:

['music']

{'name': 'lionel', 'hobbies': ['music', 'play', 'read']}

View Code

六、集合(Set)

set()函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

定义方式:

{}内用逗号分割,每个元素都必须是不可变类型,元素不能重复,无序。

s={1,2,3,1} #本质 s=set({1,2,3})

print(s)

用途:

关系运算,去重

集合常用操作

1、统计集合长度(len)

s={1,2,3,1}print(len(s))

执行结果:3

View Code

2、集合的成员运算(in和not in)

names={'lionel','wang'}print('wang' innames)

执行结果:

True

View Code

3、合集( | ):两个集合所有的元素

pythons={'egon','axx','ysb','wxx'}

linuxs={'egon','oldboy','oldgirl','smallboy','smallgirl'}print(pythons |linuxs)print(pythons.union(linuxs))

执行结果:

{'oldboy', 'axx', 'ysb', 'wxx', 'smallgirl', 'oldgirl', 'egon', 'smallboy'}

{'oldboy', 'axx', 'ysb', 'wxx', 'smallgirl', 'oldgirl', 'egon', 'smallboy'}

View Code

4、交集( & ):既属于A集合又属于B集合

pythons={'egon','axx','ysb','wxx'}

linuxs={'egon','oldboy','oldgirl','smallboy','smallgirl'}print(pythons &linuxs)print(pythons.intersection(linuxs))

执行结果:

{'egon'}

{'egon'}

View Code

5、差集( - ):所有属于A且不属于B的元素构成的集合

pythons={'egon','axx','ysb','wxx'}

linuxs={'egon','oldboy','oldgirl','smallboy','smallgirl'}print(pythons -linuxs)print(pythons.difference(linuxs))

执行结果:

{'ysb', 'wxx', 'axx'}

{'ysb', 'wxx', 'axx'}

View Code

6、对称差集( ^ ):没有同时出现在两个集合中的元素

pythons={'egon','axx','ysb','wxx'}

linuxs={'egon','oldboy','oldgirl','smallboy','smallgirl'}print(pythons ^linuxs)print(pythons.symmetric_difference(linuxs))

执行结果:

{'ysb', 'smallboy', 'axx', 'oldgirl', 'smallgirl', 'wxx', 'oldboy'}

{'ysb', 'smallboy', 'axx', 'oldgirl', 'smallgirl', 'wxx', 'oldboy'}

View Code

7、父集:>,>=

s1={1,2,3}

s2={1,2}print(s1 >s2)print(s1.issuperset(s2))

执行结果:

True

True

View Code

8、子集:

s1={1,2,3}

s2={1,2}print(s2

执行结果:

True

True

View Code

9、遍历字典

linuxs={'egon','oldboy','oldgirl','smallboy','smallgirl'}for stu inlinuxs:print(stu)

View Code

10、difference()和difference_update()区别

difference()表示集合A中存在,但是在B中不存在的元素,操作之后可以输出返回值查看。

difference_update()表示集合A中存在,但是在集合B中不存在的元素,并更新A集合,没有返回值。

s1={1,2,3}

s2={1,2}print(s1 -s2)print(s1.difference(s2))

s1.difference_update(s2)print(s1)

执行结果:

{3}

{3}

{3}

View Code

11、集合的删除(pop)

#随机删除集合中的一个元素

s2={1,2,3,4,5,'a'}print(s2.pop())

执行结果:1

View Code

12、集合的添加(add)

#向集合中添加元素,位置随机

s2={1,2,3,4,5,'a'}

s2.add('b')print(s2)

执行结果:

{1, 2, 3, 4, 5, 'b', 'a'}

View Code

13、删除的元素不存在,不报错(discard)

s2={1,2,3,4,5,'a'}

s2.discard('b')print(s2)

s2.discard('a')print(s2)

执行结果:

{'a', 1, 2, 3, 4, 5}

{1, 2, 3, 4, 5}

View Code

14、删除的元素不存在,则报错(remove)

s2={1,2,3,4,5,'a'}

s2.remove('b')print(s2)

执行结果:

Traceback (most recent call last):

File"/Users/wangzhiwei/python/day2/8 集合.py", line 95, in s2.remove('b')

KeyError:'b'

View Code

15、两个集合没有共同部分时,返回值为True

s1={1,2,3,4,5,'a'}

s2={'b','c'}print(s1.isdisjoint(s2))

执行结果:

True

View Code

16、更新集合

s2={1,2,3,4,5,'a'}

s2.update({6,7,8})print(s2)

执行结果:

{1, 2, 3, 4, 5, 6, 7, 8, 'a'}

View Code

七、数据类型总结

按存储空间的占用比(从低到高)

数字

字符串

集合:无序,即无序存索引相关信息

元组:有序,需要存索引相关信息,不可变

列表:有序,需要存索引相关信息,可变,需要处理数据的增删改

字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改

按存储空间的占用区分(从低到高)

标量/原子类型

数字,字符串

容器类型

列表,元组,字典

按可变与不可变区分

可变

列表,字典

不可变

数字,字符串,元组

按访问顺序区分

直接访问

数字

顺序访问(序列类型)

字符串,列表,元组

key值访问(映射类型)

字典

第2章 练习

#要求:#1、打印省、市、县三级菜单#2、可返回上一级#3、可随时退出程序

#!/usr/bin/env python#-*- coding: utf-8 -*-#Author: Lionel Wang

menu={'北京':{'海淀':{'五道口':{'soho':{},'网易':{},'google':{}

},'中关村':{'爱奇艺':{},'汽车之家':{},'youku':{},

},'上地':{'百度':{},

},

},'昌平':{'沙河':{'老男孩':{},'北航':{},

},'天通苑':{},'回龙观':{},

},'朝阳':{},'东城':{},

},'上海':{'闵行':{"人民广场":{'炸鸡店':{}

}

},'闸北':{'火车战':{'携程':{}

}

},'浦东':{},

},'山东':{},

}

l=[]whileTrue:for k inmenu:print(k)

choice= input('>>:').strip()if choice == 'quit' or choice == 'exit':break

if choice == 'back':if len(l) == 0:break

print(menu)

menu=l.pop()print(menu)print(l)continue

if choice not in menu:continuel.append(menu)print(l)

menu=menu[choice]

View Code

python中difference_update_Python学习笔记-Python基础(二)相关推荐

  1. python中head_python学习笔记[headfirst]

    1内置函数 (BIF) python中有很多内置函数,再遇到一个需求时候,优先考虑内置函数.内置函数使用的时候不需要导入命名空间 range():生成一个从0到某个数的数字列表 2从文件读取数据 2. ...

  2. python起步输入-[转载]python核心编程学习笔记-python起步

    python通过两种方式来实现你的需求:语句和表达式 语句:使用关键字组成命令 >>> print 'Hello wolrd!' Hello wolrd! 表达式:可以是算术表达式或 ...

  3. Python学习笔记之基础(二)变量和类型

    1. 创建变量,输出变量 savings = 100 print(savings) 2. 变量运算 savings = 100 factor = 1.10 result = savings * fac ...

  4. python中isleap_Python学习笔记(十三)系统

    使用计算机时,经常需要列出一个文件夹或者目录的内容,创建和删除文件等操作,在 Python 程序中可以做到同样的事, 甚至能做更多的事.Python 在模块 os(操作系统,operating sys ...

  5. 《python自动化》学习笔记:正则表达式基础知识

    模式匹配与正则表达式 匹配步骤: 1用 import re 导入正则表达式模块 2.用 re.compile()函数创建一个 Regex 对象 ​ 3.向 Regex 对象的 search()方法传入 ...

  6. Python基础学习笔记之(二)

    Python基础学习笔记之(二) zouxy09@qq.com http://blog.csdn.net/zouxy09 六.包与模块 1.模块module Python中每一个.py脚本定义一个模块 ...

  7. Python学习笔记_1_基础_2:数据运算、bytes数据类型、.pyc文件(什么鬼)

    Python学习笔记_1_基础_2:数据运算.bytes数据类型..pyc文件(什么鬼) 一.数据运算 Python数据运算感觉和C++,Java没有太大的差异,百度一大堆,这里就不想写了.比较有意思 ...

  8. 无敌python爬虫教程学习笔记(二)

    系列文章目录 无敌python爬虫教程学习笔记(一) 无敌python爬虫教程学习笔记(二) 无敌python爬虫教程学习笔记(三) 无敌python爬虫教程学习笔记(四) 手刃一个小爬虫 系列文章目 ...

  9. Python入门学习笔记1-Python基础

    Python入门学习笔记1-Python基础 前言:本文介绍了Python学习的前导知识概念以及必记基础函数,如善用help方法查看帮助文档,以及内置对象类型的概念以及常用函数的详解. 一.Pytho ...

  10. python input 拖入路径 去除转义 空格_python学习笔记(基础-2)(转载)

    1.输出 用print()在括号中加上字符串,就可以向屏幕上输出指定的文字. 2.输入 如果要让用户从电脑输入一些字符怎么办?Python提供了一个input(),可以让用户输入字符串,并存放到一个变 ...

最新文章

  1. java程序设计_Java程序设计:学习笔记(4-5)(未完工)
  2. Linux-unit12
  3. RTX 3090 AI性能实测:FP32训练速度提升50%,张量核心缩水
  4. 软件常见故障的现象、故障排除的方法
  5. OpenSSH(ssh + scp)+Telnet
  6. 【NIPS2018】Spotlight及Oral论文汇总
  7. 数据膨胀了?你的数仓又没有空间了?
  8. 解决WINDOWS 7中显示摄像头的简易方法
  9. 华为机试HJ15:求int型正整数在内存中存储时1的个数
  10. 计算机课程之间的关系
  11. Mac下安装DBeaver
  12. wps英文参考文献怎么对齐_wps英文参考文献怎么对齐_【论文攻略】排版技巧——如何用 Word 编辑参考文献......
  13. HyperLynx(八)带状线串扰的仿真
  14. origin如何绘制双y轴曲线_如何在origin图中,做出双Y轴?
  15. 在控制台,打印出某个具体的变量,并监听其变化
  16. Linux网络配置完全正确却ping不通易忽略的地方
  17. tyvj 2075 借教室 题解
  18. python学习——tsv文件批量转为csv文件、csv文件列合并
  19. 64位 regsrv win10_win10 专业版 64位 系统 频繁蓝屏,MEMORY_MANAGEMENT - Microsoft Community...
  20. python3.7教程百度云盘_Python新手教程百度网盘《怎么安装python3.7》

热门文章

  1. 上海交通大学教授金耀辉:AI在智慧法院中的应用
  2. 什么是webservice
  3. Contextual Diversity for Active Learning阅读笔记
  4. 计算机毕业设计之疫情防疫信息化管理系统
  5. Ralph and Mushrooms (tarjan+dp)
  6. vue报错“NavigationDuplicat: Avoided redundant navigation to current location”解决方法
  7. 分布式系统:FastRPC eRPC
  8. 一些方便的LaTex在线编辑工具
  9. 钕铁硼的尺寸与形位公差
  10. The RFB Protocol(RFB协议)简介