Python3 中有六个标准的数据类型:
Number(数字)
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)
Python3 的六个标准数据类型中:
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。
列表,字典,元祖,集合
列表(list): [ ];可变,有序;元素是任何类型的数据
增:append, insert, extend
删:del, remove, pop, clear
改:列表[下标] = 新值
查:列表[下标], 切片, 遍历
字典(dict): { };可变,无序;元素是键值对,键是不可变的唯一的,值可以是任何类型的数据
增:字典[key] = 值, setdefault(key,默认值),update
删:del, pop, clear
改:字典[key] = 值
查:字典[key], 字典.get(key), 字典.get(key,默认值),遍历
元祖(tuple): ( );不可变,有序;元素是任何类型的数据
查:和列表一样
tuple1 = 2, 34, 90, 18, 90
tuple2 = ('abc',)
x,y = (10, 20)
x,y = 10, 20
*nums, x, y = tuple1
集合(set): { };可变,无序;元素是不可变的唯一的
增:add, update
删:remove
查:遍历
集合运算:包含(>=, <=),并集(|)、交集(&)、差集(-)、补集(^)
===========================================================
a=[1,2]
b=a.copy()
b.append(3)
print(a,b,sep='\n')
#[1, 2]
#[1, 2, 3]
print('=========')
拷贝:将变量中的值复制一份,产生新的数据。然后将新的数据对应的地址返回。
浅拷贝:直接拷贝地址;切片和copy()都是浅拷贝
深拷贝:将地址对应的值拷贝一份,并将值赋予新地址;copy.deepcopy()深拷贝
import copy
x1=[1,2]
x2=(8,9)
list1=[x1,x2]
list2=list1.copy() #list2对list1进行浅拷贝
list3=copy.deepcopy(list1) #list3对list1进行深拷贝
print(list1,list2,list3,sep='\n')
# [[1, 2], (8, 9)]
# [[1, 2], (8, 9)]
# [[1, 2], (8, 9)]
print('=========')
list2[0].append(3) #list2的第一个元素发生变化,list1的第一个元素跟着发生变化;
list3[0].append(7) #list3的第一个元素发生变化,list1的第一个元素不发生变化;
print(list1,list2,list3,sep='\n')
# [[1, 2, 3], (8, 9)]
# [[1, 2, 3], (8, 9)]
# [[1, 2, 7], (8, 9)]
列表的元素和字典的值可以是任何类型的数据
1、列表中有字典
找到年龄最大的学生,返回姓名和年龄
persons=[
{'name':'张三','age':25,'sex':'男'},
{'name':'李四','age':27,'sex':'男'},
{'name':'王二','age':24,'sex':'女'}]
max1=0
name=""
for person in persons:
print(person)
age=person['age']
if age>max1:
max1=age
name=person['name']
print(name,max1) #李四 27
2、字典中有列表
存在一个班级,包含有班级名、位置、学生,学生信息包含有姓名,年龄,性别;
class1={
'classname':'Python1807',
'location':'18-6',
'student':[{'name':'张三','age':25,'sex':'男'},
{'name':'李四','age':27,'sex':'男'},
{'name':'王二','age':24,'sex':'女'}]}
print(class1['student'][2]['sex'])
练习:在班级里添加一个学生,姓名老王,年龄40,学校北大青鸟
name=input('请输入姓名:')
age=input('请输入年龄:')
school=input('请输入学校:')
student={'name':name,'age':age,'school':school}
class1['student'].append(student)
print(class1['student'])
练习:删除年龄大于25 的学生
all_student=class1['student']
for person in all_student[:]:
if person['age']>25:
all_student.remove(person)
print(all_student)
网友评论