可变与不可变类型
不可变类型
如:字符串(str)、整型(int)、浮点型(float)
特点:值改变了,内存地址也改变、其实改变的不是原值、而是改变之后又生成一块空间来保存新值
可变类型
如:列表(list)、字典(dict)
特点:值改变了,内存地址没有改变,其实改变的是原值,只要你改变了只,原来的值就会发生变化
内置方法
一、列表的内置方法(续)
1.reverse方法
作用:颠倒列表内元素顺序
# 使用方法
list.reverse()
2.sort方法
作用:给列表内所有元素排序
# 使用方法
l = [11, 2, 33, 4, 5]
# 升序排列
print(l.sort())
# 降序排列
print(l.sort(reverse=True))
二、字典的内置方法
定义方式
1. info={'name':'tony','age':18,'sex':'male'}
# info={'age': 18, 'sex': 'male', 'name': 'tony'}
2. info=dict(name='tony',age=18,sex='male')
print(dic['name'])
print(dic['age'])
print(dic['hobby'][1])
字典的其他用法
dic = {
'name': 'xxx',
'age': 18,
'hobby': ['play game', 'basketball']
}
1.取值
print(dic['name'])
print(dic['age'])
print(dic['hobby'][1])
2.赋值操作
如果key已经在字典中存在,那么,就是对原来的值进行修改,如果不存在key值,就是新增一个键值对
# {'name': 'xxx', 'age': 18, 'hobby': ['play game', 'basketball'], 'gender': 'male'}
dic['gender'] = 'male'
# {'name': 'jerry', 'age': 18, 'hobby': ['play game', 'basketball'], 'gender': 'male'}
dic['name'] = 'jerry'
print(dic)
print(len(dic)) # 3
print('name' in dic)
dic.pop('name') # pop expected at least 1 argument, got 0
dic.pop('age') # pop expected at least 1 argument, got 0
print(dic)
'''字典的三剑客'''
keys values items
keys方法把字典中得所有的key值组织成一个列表:
dict_keys(['name', 'age', 'hobby'])
print(dic.keys())
for i in dic.keys():
print(i)
values方法把字典中得所有的value值组织成一个列表:
print(dic.values()) # dict_values(['xxx', 18, ['play game', 'basketball']])
for i in dic.values():
print(i)
dict_items([('name', 'xxx'), ('age', 18), ('hobby', ['play game', 'basketball'])])
print(dic.items())
for i in dic.items():
print(i[0], i[1]) # ('name', 'age')
for i, j in dic.items(): #
print(i , j) # ('name', 'xxx')
字典需要掌握的操作
1.get取值:
print(dic.get('name')) # xxx
print(dic.get('age'))
print(dic.get('hobby'))
print(dic.get('name1')) # None
'''get方法获取key不存在的时候,不会报错,会返回None,另外,还可以设置默认值'''
# print(dic.get('name1', 666)) # 666
"""以后字典取值推荐使用get方法,中括号取值是可以用的"""
dic = {
'name': 'xxx',
'age': 18,
'hobby': ['play game', 'basketball']
}
print(dic.popitem()) # ('hobby', ['play game', 'basketball'])
print(dic) # {'name': 'xxx', 'age': 18}
2.update方法
如果key值存在,则为修改,如果不存在,则为添加
dic.update({'name': "jerry", 'gender': 'male'}) # 要记忆
# {'name': 'jerry', 'age': 18, 'hobby': ['play game', 'basketball'], 'gender': 'male'}
print(dic)
# dic = dict.fromkeys(['k1','k2','k3'],[])
# dic = dict.fromkeys(['k1','k2','k3'],[666]) # {'k1': [666], 'k2': [666], 'k3': [666]}
# dic = dict.fromkeys(['k1','k2','k3'],[666, 888]) # {'k1': [666, 888], 'k2': [666, 888], 'k3': [666, 888]}
print(dic) # {'k1': [], 'k2': [], 'k3': []} # 初始化变量
print(dic['k1'])
print(dic['k2'])
print(dic['k3'])
dic['k1'].append('hello world') # {'k1': [666, 888, 'hello world'], 'k2': [666, 888, 'hello world'], 'k3': [666, 888, 'hello world']}
print(dic)
dic = {
'name': 'xxx',
'age': 18,
'hobby': ['play game', 'basketball']
}
'''setdefault:如果key值存在,则直接获取key对应的value值,如果不存在,就返回第二个参数的值'''
print(dic.setdefault('name', 666)) # xxx
print(dic.setdefault('name1', 666)) # 666
三、元组的内置方法
作用:元组与列表类似,也是可以存多个任意类型的元素,不同之处在于元组的元素不能修改,即元组相当于不可变的列表,'用于记录多个固定不允许修改的值,单纯用于取'
定义方式:
countries = ("中国","美国","英国") # 常见的
本质:countries = tuple("中国","美国","英国")
类型转换
print(tuple(123)) # 'int' object is not iterable
print(tuple(123.1)) # 'float' object is not iterable
print(tuple('hello')) # ('h', 'e', 'l', 'l', 'o')
print(tuple((1,2 ,3 ,4))) # (1, 2, 3, 4)
print(tuple([1, 2, 3, 4])) # (1, 2, 3, 4)
print(tuple({'username':'kevin', 'age':18})) # ('username', 'age')
print(tuple({1, 2, 3, 4})) # (1, 2, 3, 4)
"""所有能够支持for循环的数据类型都可以转为元组类型"""
使用方法
# 内部可以存放任意的数据类型
tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33)
'''元组就是不可变的列表'''
print(tuple1[0])
print(tuple1[2])
print(tuple1[-1])
print(tuple1[-2])
tuple1[0] = 666 # TypeError: 'tuple' object does not support item assignment
# 切片操作跟列表一样一样的
print(tuple1[0:6:2]) # (1, 15000.0, 22)
print(len(tuple1)) # 6
print('hhaha' not in tuple1)
for i in tuple1:
print(i)
扩展练习:
res = (111, ) # <class 'int'>
res1 = (123.1,) # <class 'float'>
res2 = ('hello',) # <class 'str'>
'''元组内部如果只有一个元组也要加逗号,否则就不是元组,只有加了逗号才是元组'''
'''以后只要是容器类型的数据类型,内部只要只有一个元素,末尾都推荐加一个逗号'''
"""
容器类型:只要是内部能够存放多个元素的都可以称为是容器类型
eg:list dict tuple set
不是容器类型的:int float str bool
"""
print(type(res), type(res1), type(res2)) # <class 'tuple'> <class 'tuple'> <class 'tuple'>
print(res, res1, res2)
res3 = [111]
res4 = ['hello']
print(type(res3), type(res4)) # <class 'list'> <class 'list'>
res5 = () # <class 'tuple'>
res6 = tuple()
print(type(res5))
"""第二题:"""
t = (11, 22, 33, 44, [1, 2, 3, 4])
# t[0] = 666 # 对还是不对?
t[4][0] = 666 # 对还是不对?
print(t)
四、集合的内置方法
1. 如何定义集合
s = set() # 空集合
2.集合的作用
集合、list、tuple、dict一样都可以存放多个值,但是集合主要用于:去重、关系运算
3.类型转换
s = set([1,2,3,4])
s1 = set((1,2,3,4))
s2 = set({'name':'jason',})
s3 = set('egon')
# s,s1,s2,s3
# {1, 2, 3, 4} {1, 2, 3, 4} {'name'} {'e', 'o', 'g', 'n'}
4.去重方法
## 1. 去重
name_list = ['kevin', 'jerry', 'tony', 'oscar', 'tony', 'oscar', 'jerry', ]
## 要求:去除重复元素
# 思路:列表------------>集合
s = set(name_list) # {'kevin', 'tony', 'jerry', 'oscar'}
print(s)
# 在把集合转为列表
print(list(s)) # ['tony', 'oscar', 'jerry', 'kevin']
'''集合的另外一个特点:无序'''
###
ll = [11, 22, 4, 55, 3, 66, 77, 99, 88, 10, 20, 30, 66, 77, 99, 88,]
# 1. 去重
# 转为集合
# 2. 去重之后,保留原来的位置
# 思路:循环 遍历
# 1. 先定义一个空列表来存储去重之后的结果
new_list = []
# 2. 循环遍历
for i in ll:
# 判断new_list这个列表中是否已经存在这个值,如果存在了,就不在添加,如果不存在,则追加进去
if i not in new_list:
new_list.append(i)
# 如果在的话,就不用管了
print(new_list) # [11, 22, 4, 55, 3, 66, 77, 99, 88, 10, 20, 30]
5.集合运算
friends1 = {"zero", "kevin", "jason", "egon"} # 用户1的好友们
friends2 = {"Jy", "ricky", "jason", "egon"} # 用户2的好友们
print(friends1)
# # 1.合集/并集(|):求两个用户所有的好友(重复好友只留一个)
# 集合嫩不嫩单个取值?
print(friends1 | friends2) # {'Jy', 'ricky', 'egon', 'kevin', 'jason', 'zero'}-------[]
# 2.交集(&):求两个用户的共同好友
print(friends1 & friends2) # {'jason', 'egon'}
# # 3.差集(-):
# >>> friends1 - friends2 # 求用户1独有的好友
print(friends1 - friends2) # {'zero', 'kevin'}
print(friends2 - friends1) # {'Jy', 'ricky'}
# 4.对称差集(^) # 求两个用户独有的好友们(即去掉共有的好友)
print(friends1 ^ friends2) # {'Jy', 'kevin', 'zero', 'ricky'}
# 5.值是否相等(==)
# >>> friends1 == friends2
print(friends1 == friends2) # False
# 6.父集:一个集合是否包含另外一个集合
# 6.1 包含则返回True
# >>> {1,2,3} > {1,2}
print({1, 2, 3} > {1, 2}) # True
# 7.子集
print({1, 2, 3} < {1, 2}) # True