day2_python之数据类型常用操作方法

一、什么可变数据类型和不可变数据类型

  可变数据类型:value值改变,id值不变;不可变数据类型:value值改变,id值也随之改变。

  如何确定一种数据类型是可变的还是不可变的:

  根据可变数据类型与不可变数据类型的概念,只需要在改变value值的同时,使用id()函数查看变量id值是否变化就可以知道这种数据类型是可变的还是不可变的了。

核心提示:

可变类型 Vs 不可变类型

可变类型(mutable):列表,字典

不可变类型(unmutable):数字,字符串,元组

这里的可变不可变,是指内存中的那块内容(value)是否可以被改变

二、什么是数据类型?

我们人类可以很容易的分清数字与字符的区别,但是计算机并不能呀,计算机虽然很强大,但从某种角度上看又很傻,除非你明确的告诉它,1是数字,“汉”是文字,否则它是分不清1和‘汉’的区别的,因此,在每个编程语言里都会有一个叫数据类型的东东,其实就是对常用的各种数据类型进行了明确的划分,你想让计算机进行数值运算,你就传数字给它,你想让他处理文字,就传字符串类型给他。

2.1、int(整型)

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

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

long(长整型)

跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。

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

整型与浮点型

#整型int
  作用:年纪,等级,身份证号,qq号等整型数字相关
  定义:
    age=10 #本质age=int(10)

#浮点型float
  作用:薪资,身高,体重,体质参数等浮点数相关

    salary=3000.3 #本质salary=float(3000.3)

#二进制,十进制,八进制,十六进制

2.2、字符串

在Python中,加了引号的字符都被认为是字符串!

#作用:名字,性别,国籍,地址等描述信息

#定义:在单引号双引号三引号内,由一串字符组成
name='egon'

#优先掌握的操作:
按索引取值(正向取+反向取) :只能取
切片(顾头不顾尾,步长)
长度len
成员运算in和not in


移除空白strip
切分split
循环  
>>> name = "Alex Li" #双引号
>>> age = "22"       #只要加引号就是字符串
>>> age2 = 22          #int
>>>
>>> msg = '''My name is Alex, I am 22 years old!'''  #我擦,3个引号也可以
>>>
>>> hometown = 'ShanDong'   #单引号也可以

那单引号、双引号、多引号有什么区别呢? 让我大声告诉你,单双引号木有任何区别,只有下面这种情况 你需要考虑单双的配合  

msg = "My name is Alex , I'm 22 years old!"

多引号什么作用呢?作用就是多行字符串必须用多引号  

msg = '''
今天我想写首小诗,
歌颂我的同桌,
你看他那乌黑的短发,
好像一只炸毛鸡。
'''
 
print(msg)

字符串拼接

数字可以进行加减乘除等运算,字符串呢?让我大声告诉你,也能?what ?是的,但只能进行"相加"和"相乘"运算。

>>> name
'Alex Li'
>>> age
'22'
>>>
>>> name + age  #相加其实就是简单拼接
'Alex Li22'
>>>
>>> name * 10 #相乘其实就是复制自己多少次,再拼接在一起
'Alex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex LiAlex Li'

注意,字符串的拼接只能是双方都是字符串,不能跟数字或其它类型拼接  

>>> type(name),type(age2)
(<type 'str'>, <type 'int'>)
>>>
>>> name
'Alex Li'
>>> age2
22
>>> name + age2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects #错误提示数字 和 字符 不能拼接

字符串常用操作

#####strip########
name='*xiechao**'
print(name.strip('*')) #输出:xiechao  ,去掉所有*号
print(name.lstrip('*'))  #输出:xiechao**  ,去左边的星号
print(name.rstrip('*')) #输出:*xiechao  ,去掉右边的星号

####startswith,endswith######
name = 'wangyanli_SB'
print(name.endswith('SB'))  #判断以什么结尾,返回True
print(name.startswith('wangyanli'))#判断以什么开头,返回True

####replace,替换######
name='dog say :i have one tesla,my name is dog'
print(name.replace('dog','SB',1)) #匹配dog替换成sb,1次

##format的四种种玩法####
res = '{} {} {}'.format('xiechao', 23, 'male')  # 输出xiechao 23 male
res = '{1} {0} {1}'.format('xiechao', 18, 'male')  # 输出18 xiechao 18
res = '{name} {age} {sex}'.format(sex='male', name='xiechao', age=18)#输出xiechao 18 male
res = 'Name:{name} Age:{age} Sex:{sex}'.format(sex='male', name='xiechao', age=18)#Name:xiechao Age:18 Sex:male
print(res)



###find,rfind,index,rindex,count####
name='xiechao say hello'
print(name.find('o',1,3)) #find:顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
print(name.index('e',2,4)) #同上,但是找不到会报错
print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有


####3#split:切分
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默认分隔符为空格
name='C:/a/b/c/d.txt' #只想拿到顶级目录
print(name.split('/',1)) #1表示按列表内的第一个元素进行切分

name='a|b|c'
print(name.rsplit('|',1)) #从右开始切分


#####join,拼接
tag=' '
print(tag.join(['xiechao','say','hello','world','D:/''A''/''bat'])) #可迭代对象必须都是字符串

#####center,ljust,rjust,zfill
name='xiechao'
print(name.center(30,'-')) #输出:-----------xiechao------------
print(name.ljust(30,'*')) #输出 :xiechao***********************
print(name.rjust(30,'*'))#输出:***********************xiechao
print(name.zfill(50)) #用0填充  输出:0000000000000000000000000000000000000000000xiechao


#expandtabs
name='xiechao	hello'
print(name)    #tab符号
print(name.expandtabs(1))

#lower,upper
name='xiechao'
print(name.lower())#xiechao
print(name.upper()) #XIECHAO


#captalize,swapcase,title
print(name.capitalize()) #首字母大写
print(name.swapcase()) #大小写翻转
msg='xiechao 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='xiechao123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成
#
print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle())

2.3、列表常用操作

my_girl_friends = ['alex', 'wupeiqi', 'yuanhao', 4, 10, 30]
my_girl_friends = list(['alex', 'wupeiqi', 'yuanhao', 4, 10, 30])

print(type(my_girl_friends))

print(my_girl_friends[2])

print(my_girl_friends[1:3])#['wupeiqi', 'yuanhao']


####.append追加值
my_girl_friends = ['alex', 'wupeiqi', 'yuanhao', 4, 10, 30]
my_girl_friends.append('oldboy')
print(my_girl_friends)







#######.pop按照索引删值,如果不指定索引默认是从右边开始删值
my_girl_friends = ['alex', 'wupeiqi', 'yuanhao', 4, 10, 30, 'oldboy']
print(my_girl_friends.pop())
my_girl_friends.pop()
my_girl_friends.pop(0)
my_girl_friends.pop(0)
my_girl_friends.pop(1)




#######.remove按照值去删除
my_girl_friends = ['alex', 'wupeiqi', 'yuanhao', 4, 10, 30, 'oldboy']
my_girl_friends.remove('yuanhao')
print(my_girl_friends)


####len()统计长度
my_girl_friends = ['alex', 'wupeiqi', 'yuanhao', 4, 10, 30, 'oldboy']
my_girl_friends.__len__()
print(len(my_girl_friends))



####in,什么有没有在里边
my_girl_friends = ['alex', 'wupeiqi', 'yuanhao', 4, 10, 30, 'oldboy']
print('wupeiqi' in my_girl_friends)

msg='my name is egon111111'
print('egon' in msg)





####其他操作(掌握)  .insert按照索引插入值
my_girl_friends = ['alex', 'wupeiqi', 'alex', 'yuanhao', 4, 10, 30]
my_girl_friends.insert(1, 'Sb')
print(my_girl_friends)




#####其他操作(了解).clear清空列表
my_girl_friends=['alex','wupeiqi','alex','yuanhao',4,10,30]
my_girl_friends.clear()
print(my_girl_friends)



#####其他操作(了解).copy() 复制列表
my_girl_friends=['alex','wupeiqi','alex','yuanhao',4,10,30]
l=my_girl_friends.copy()
print(l)


#####其他操作(了解).count ,统计某一个元素在列表里出现了几次
my_girl_friends=['alex','wupeiqi','alex','yuanhao',4,10,30]
print(my_girl_friends.count('alex'))





#####其他操作(了解).extend,扩展,append一次只能加一个值,entend一次可以追加多个值
my_girl_friends=['alex','wupeiqi','alex','yuanhao',4,10,30]
my_girl_friends.append('oldboy1')
my_girl_friends.append('oldboy2')
my_girl_friends.append('oldboy3')
print(my_girl_friends)

my_girl_friends.extend(['oldboy1','oldboy2','oldboy3'])
print(my_girl_friends)


#####其他操作(了解).reverse,反转,列表元素倒过来显示
my_girl_friends = ['alex', 'wupeiqi', 'alex', 'yuanhao', 4, 10, 30]
print(my_girl_friends.index('alex'))
my_girl_friends.reverse()
print(my_girl_friends)

l=[3,-1,5,2]
l.sort(reverse=True)
print(l)



##练习一:
data=['alex',84,[1900,3,38]]
# print(data[0])
# print(data[1])
print(data[2][0])
#####++++++++++++++++++++++++++++++++++++

###按照索引一个一个得给列表传值
data=['alex',84,[1900,3,38]]
name,age,birth=data
print(name)
print(age)
print(data)
print(birth)#输出:
####++++++++++

msg='hello'
a,b,c,d,e=msg
print(a,b,c,d,e)#输出:h e l l o
######++++++

msg='hello'
a,_,_,_,b=msg
print(a)
print(b)

a,*_,b=msg
print(a,b)

######+++++++++++++++++++++++++++++
####队列:先进先出
fifo=[]
####入队
fifo.append('first')
fifo.append('second')
fifo.append('third')
print(fifo)
#####出队
print(fifo.pop(0))
print(fifo.pop(0))
print(fifo.pop(0))


#######################
####入队
fifo=[]
fifo.insert(0,'first')
fifo.insert(0,'second')
fifo.insert(0,'third')
print(fifo)

######出队
print(fifo.pop())
print(fifo.pop())
print(fifo.pop())



堆栈:先进后出
lifo=[] 

2.4、布尔型(bool)

布尔类型很简单,就两个值 ,一个True(真),一个False(假), 主要用记逻辑判断

但其实你们并不明白对么? let me explain, 我现在有2个值 , a=3, b=5 , 我说a>b你说成立么? 我们当然知道不成立,但问题是计算机怎么去描述这成不成立呢?或者说a< b是成立,计算机怎么描述这是成立呢?

没错,答案就是,用布尔类型

>>> a=3
>>> b=5
>>>
>>> a > b #不成立就是False,即假
False
>>>
>>> a < b #成立就是True, 即真
True

计算机为什么要描述这种条件呢?因为接下来就可以根据条件结果来干不同的事情啦呀!比如  

if a > b
   print(a is bigger than b )
 
else
   print(a is smaller than b )

2.5、元组常用操作 

元组:用来存放多个值,对于列表老说,元组不可变,主要用来读
#####元组:用来存放多个值,对于列表老说,元组不可变,主要用来读

age=(11,22,33,44,55,33)# 本质age=tuple((11,22,33,44,55))
print(age)
print(age[2])#33
print(age[1:4])#(22, 33, 44)
print(len(age))#6
print(11 in age)#True

print(age.index(33))#2  查看33的索引
print(age.count(33))#2  统计33出现的次数


#####元组练习
msg_dic = {
    'apple': 10,
    'tesla': 100000,
    'mac': 3000,
    'lenovo': 30000,
    'chicken': 10,
}
goods_l = []

while True:
    for key in msg_dic:
        # print('Goods Name:%s Price:%s' %(key,msg_dic[key]))
        print('33[31;1mName:{name} Price:{price}33[0m'.format(price=msg_dic[key], name=key))
    choice = input('your goods name>>: ').strip()
    if len(choice) == 0 or choice not in msg_dic: continue
    count = input('your count>>: ').strip()
    if count.isdigit():
        goods_l.append((choice, msg_dic[choice], int(count)))
    print(goods_l)

2.6、字典的常用操作方法

info = {'name': 'egon', 'age': 18, 'sex': 'male'}  # 本质info=dict({'name':'egon','age':18,'sex':'male'})
print(info['age'])  # 取值
info['height'] = 1.80  # 增加值

print(info)

for key in info:
    print(key)

####字典的key必须是不可变类型,也成为可hash类型

##元组也可以当作字典的Key
info = {(1, 2): 'a'}
print(info[(1, 2)])

#####字典常用的方法.pop( key ,default)删除值
info = {'name': 'egon', 'age': 18, 'sex': 'male'}
print(info.pop('name'))
print(info)
print(info.pop('asdfsadfasdfasfasdfasdfasdf', None))

####字典常用的方法.get(key ,default) 获取值,与通过key取值的区别在于,对于没有的值,返回None,不会报错
info = {'name': 'egon', 'age': 18, 'sex': 'male'}
# print(info['name1'])#KeyError: 'name1'
print(info.get('name1'))
print(info.get('nameasdfasdfasdfasdf', 'not key'))  # not key

######.popitem,往外弹值,与pop不同的是,pop通过key来删除值
info = {'name': 'egon', 'age': 18, 'sex': 'male'}
print(info.popitem())  # ('sex', 'male')
print(info.popitem())  # ('age', 18)
print(info)

info = {'name': 'egon', 'age': 18, 'sex': 'male'}
print(info.keys(), type(info.keys()))  # dict_keys(['name', 'age', 'sex']) <class 'dict_keys'>
print(info.values())  # dict_values(['egon', 18, 'male'])

for key in info.keys():  # 取字典所有的key ,不写.keys()默认也是访问的Key
    print(key)

info = {'name': 'egon', 'age': 18, 'sex': 'male'}
for key in info.values():  # 取字典所有的values
    print(key)

info = {'name': 'egon', 'age': 18, 'sex': 'male'}
for key in info:  # 取字典所有的内容
    print(key, info[key])

info = {'name': 'egon', 'age': 18, 'sex': 'male'}
print(info.items())
for key, value in info.items():  # key,value=('name','egon')
    print(key, value)

#######.clear 清空
info = {'name': 'egon', 'age': 18, 'sex': 'male'}
info.clear()
print(info)

#######.fromkeys创建一个字典
info = {'name': 'egon', 'age': 18, 'sex': 'male'}
print(info.items())
dic = info.fromkeys(['name', 'age', 'sex'], 11111111)
print(dic)  # {'name': 11111111, 'age': 11111111, 'sex': 11111111}

dic = info.fromkeys(['name', 'age', 'sex'], None)
print(dic)  # {'name': None, 'age': None, 'sex': None}

dic = dict(a=1, b=2, c=3)
print(dic)

print(info.items())

print(dict([('name', 'egon'), ('age', 18), ('sex', 'male')]))

dic = dict.fromkeys(['name', 'age', 'sex'], 11111111)
print(dic)
print(info)

#######.update,作用:用新的字典更新老的字典
info = {'name': 'egon', 'age': 18, 'sex': 'male'}
print(info)
dic = {'a': 1, 'b': 2, 'name': 'SHUAI'}
info.update(dic)
print(info)  # {'name': 'SHUAI', 'age': 18, 'sex': 'male', 'a': 1, 'b': 2}

#######.setdefault,作用:当key对应多个值的情况下,可以用setdefault
d = {}
d['name'] = 'egon'
d['age'] = 18
d['sex'] = 'male'
d['hobby'] = []
# d['hobby'].append('play basketball')
# d['hobby'].append('play football')
print(d)
d.setdefault('hobby', []).append('play1')  # d['hobby']
d.setdefault('hobby', []).append('play2')  # d['hobby']
d.setdefault('hobby', []).append('play3')  # d['hobby']
print(d)

####字典练习:有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中
nums = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
dic = {
    'k1': [],
    'k2': [],
}
for item in nums:
    if item >= 66:
        dic['k1'].append(item)
    else:
        dic['k2'].append(item)

print(dic)

#####统计s='hello alex alex say hello sb sb'中每个单词的个数
s = 'hello alex alex say hello sb sb'
words = s.split()
# print(words)
dic = {}
for word in words:
    # print(word)
    if word not in dic:
        dic[word] = 1
        # {'hello':1,'alex':1}
    else:
        dic[word] += 1

print(dic)

###################################
msg_dic = {
    'apple': 10,
    'tesla': 100000,
    'mac': 3000,
    'lenovo': 30000,
    'chicken': 10,
}
for key, value in msg_dic.items():
    print(key, value)

2.7、集合

作用:去重,关系运算,

定义:
可变类型是不可hash类型
不可变类型是可hash类型

定义集合:
集合:可以包含多个元素,用逗号分割,
集合的元素遵循三个原则:
1:每个元素必须是不可变类型(可hash,可作为字典的key)
2:没有重复的元素
3:无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值

优先掌握的操作:
长度len
成员运算in和not in


|合集即并集

print(pythons | linuxs)
print(pythons.union(linuxs))


&交集

print(pythons & linuxs)
print(pythons.intersection(linuxs))


-差集

print(pythons - linuxs)
print(pythons.difference(linuxs))


^对称差集

print(pythons ^ linuxs)
print(pythons.symmetric_difference(linuxs))


==


>,>= ,<,<= 父集,子集

####>=父集
s1={1,2,3,4}
s2={1,5}
print(s1 >= s2)

######<=子集
print(s1 <= s2)
print(s2 <= s1)

pythons=['alex','egon','yuanhao','wupeiqi','gangdan','biubiu']
linuxs=['wupeiqi','oldboy','gangdan']

res=[]
for p in pythons:
    if p in linuxs:
        res.append(p)

print(res)
#####关系运算???

########==================================
#####1 集合内可以有多个元素,但是每个元素都必须是不可变类型,即可hash类型
#####2 集合内的元素唯一
#####3 集合是无序的
s={1,'a',1,1,1,1,1,1} #s=set({1,'a',1,1,1,1,1,1})


s1=set('hello')
print(s1,type(s1))
s={'a',3,9,'b'}
print(s)

#####集合优先掌握的方法
pythons = {'alex', 'egon', 'yuanhao', 'wupeiqi', 'gangdan', 'biubiu'}

print('alex' not in pythons)
print(pythons)


#######集合是取不了值的,之所以叫集合是为了进行一个集合与另外一个集合的关系运算。整体与整体的比较。可以做去重操作。

#####关系运算
######&交集,求两个集合的共同部分

s1 = {1, 10, 11, 22}
s2 = {1, 11, 33}
print(s1 & s2)  #{1, 11}




#####|并集,求两个集合里所有的部分,把两个集合加一起,去掉重复的部分
s1 = {1, 10, 11, 22}
s2 = {1, 11, 33}
print(s1 | s2)#{1, 33, 10, 11, 22}


####-差集,只在一个集合里边的内部,把共同的部分去掉
s1 = {1, 10, 11, 22}
s2 = {1, 11, 33}
print(s1 - s2)#{10, 22}
print(s2 - s1)#{33}




#####^对称差集,把两个集合中重复的内容去掉,显示两个集合剩下的内容

s1 = {1, 10, 11, 22}
s2 = {1, 11, 33}
print(s1 ^ s2)#{33, 22, 10}



####>=父集
s1={1,2,3,4}
s2={1,5}
print(s1 >= s2)

######<=子集
print(s1 <= s2)
print(s2 <= s1)
#########===============================================

######集合练习一

pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}


#####求出即报名python又报名linux课程的学员名字集合
print(pythons & linuxs)
#####求出所有报名的学生名字集合
print(pythons | linuxs)
#####求出只报名python课程的学员名字
print(pythons - linuxs)
#####求出没有同时这两门课程的学员名字集合
print(pythons ^ linuxs)



####集合练习二:
#####有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序
l = ['a', 'b', 1, 'a', 'a']
s = set(l)
print(s)
print(list(s))



####在上题的基础上,保存列表原来的顺序
l = ['a', 'b', 1, 'a', 'a']

l1 = []
for item in l:
    if item not in l1:
        l1.append(item)
print(l1)
###用集合去实现保存列表原来的顺序
l = ['a', 'b', 1, 'a', 'a']
l1 = []
s = set()
for item in l:
    if item not in s:
        s.add(item)  # {'a','b',1}
        l1.append(item)

print(l1)


#########有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序

l = [
    {'name': 'egon', 'age': 18, 'sex': 'male'},
    {'name': 'alex', 'age': 73, 'sex': 'male'},
    {'name': 'egon', 'age': 20, 'sex': 'female'},
    {'name': 'egon', 'age': 18, 'sex': 'male'},
    {'name': 'egon', 'age': 18, 'sex': 'male'},
]


#####简单方法
l1 = []
for item in l:
    if item not in l1:
        l1.append(item)
print(l1)



####复杂方法
l1 = []
s = set()
for item in l:
    val = (item['name'], item['age'], item['sex'])
    print(val)
    if val not in s:
        s.add(val)
        # print(val)
        l1.append(item)

print(l1)





#####集合的内置方法
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}


####求出即报名python又报名linux课程的学员名字集合   ,求交集
print(pythons & linuxs)
print(pythons.intersection(linuxs))

####求出所有报名的学生名字集合,求并集
print(pythons | linuxs)
print(pythons.union(linuxs))


####求出只报名python课程的学员名字,求差集
print(pythons - linuxs)
print(pythons.difference(linuxs))


####求出没有同时这两门课程的学员名字集合,对称差集
print(pythons ^ linuxs)
print(pythons.symmetric_difference(linuxs))



###集合加值:.app,加的值必须是不可变类型
s={1,2,3,'a'}
s.add(4)
print(s)





###.pop删除值,这种方法不只能指定删除特定的值
s={1,2,3,'a'}
print(s.pop()) #删除值,这种方法不只能指定删除特定的值


###.remove(指定删除的值),这种方法可以指定需要删除的值
s={1,2,3,'a'}
s.remove('a')
print(s)  #{1, 2, 3}
s.remove('vvvvvvvvvv') #删除的值不存在会报错

s.discard('aaaaaa')#删除的值即使不存在也不会报错
print(s)

三、运算符

#身份运算(is ,is not)
is比较的是id,而双等号比较的是值
毫无疑问,id若相同则值肯定相同,而值相同id则不一定相同
>>> x=1234567890
>>> y=1234567890
>>> x == y
True
>>> id(x),id(y)
(3581040, 31550448)
>>> x is y
False

四、数据类型总结

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

数字
字符串
集合:无序,即无序存索引相关信息
元组:有序,需要存索引相关信息,不可变
列表:有序,需要存索引相关信息,可变,需要处理数据的增删改
字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改

按存值个数区分

标量/原子类型 数字,字符串
容器类型 列表,元组,字典

 

 

按可变不可变区分

可变 列表,字典
不可变 数字,字符串,元组

 

 

按访问顺序区分

直接访问 数字
顺序访问(序列类型) 字符串,列表,元组
key值访问(映射类型) 字典

 

   

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/xiechao621/p/7923053.html