Python入门(二)
一、列表
1.基本规则
1.初始化列表
list=[ ]
2.列表可以一次性存储多个数据
3.列表中的每一项,都能是不同的数据类型。(包括列表)
4.列表的作用是一次性存储多个数据,程序员可以对这些数据进行的操作有:增删改查
#列表的元素多种多样(指类型)
test_list = [1,'a',[1,2],{"name":"刘备"},{2,3},(1,2,"李四")]#列表的输出
names_list = ['刘备','曹操','孙权']print(names_list[0])print(names_list[1])print(names_list[2])print(names_list)
2.列表的常用操作
2.1查找
2.1.1下标查找
name_list=['tom','lily','rose']print(name_list[0]) # tomprint(name_list[1]) #lilyprint(name_list[2]) # rose
2.1.2函数(方法)查找
index(): 返回指定数据所在位置的下标
1.语法
列表序列 . index(数据,开始位置的下标,结束位置的下标)
注意:如果查找的数据不存在则报错
name_list = ['tom','lily','rose']
print(name_list.index('tom')) # 0
count():统计指定数据在当前列表中出现的次数
name_list=['tom','lily','rose']
print(name_list.count('tom')) # 1
len():可以获取列表的长度,即列表中数据的个数
name_list=['tom','lily','rose']
print(len(name_list)) # 3
2.1.3判断是否存在
in:判断指定的数据在某个列表序列,如果在返回True,否则返回False
name_list=['tom','lily','rose']print('lily'in name_list) #Trueprint('yao' in name_list) #False
not in :判断指定的数据不在某个列表序列,如果不在返回True,否则返回False
name_list=['tom','lily','rose']print('tom' not in name_list) # Falseprint('yaoyao' not in name_list) #True
name_list=['tom','lily','rose']
name = input('请输入你要搜索的名字:')
if name in name_list:print(f'您搜索的{name}存在')
else:print(f'您搜索的{name}不存在')
2.2增加
作用:增加指定数据到列表中
append():列表尾部追加数据
语法:
列表序列.append(数据)
name=['tom','lily','rose']
name.append('xiaoming')
print(name)
如果append( )追加的数据是一个序列,则追加整个序列到列表,整体新增一个元素
name_list = ['tom','lily','rose']
name_list.append(['xiaoming','xiaohong'])
# 结果:['tom', 'lily', 'rose', ['xiaoming', 'xiaohong']]
print(name_list)
insert( ): 指定位置新增数据
.语法 列表序列.insert(位置下标,数据)
name_list = ['tom','lily','rose']
name_list.insert(0,'yaoyao')
# 结果:['yaoyao', 'tom', 'lily', 'rose']
print(name_list)
extend(): 列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一加入列表中 1.语法 列表序列.extend(数据)
name_list = ['tom','lily','rose'] name_list.extend('abc') #结果:['tom', 'lily', 'rose', 'a', 'b', 'c'] print(name_list)name_list = ['tom','lily','rose'] name_list.extend(['a','b','c']) #结果:['tom', 'lily', 'rose', 'a', 'b', 'c'] print(name_list)
2.3删除
del
语法 del 目标
删除列表
name_list = ['tom','lily','rose'] del name_list #结果:NameError: name 'name_list' is not defined print(name_list)
删除指定数据
name_list = ['tom','lily','rose']del name_list[0]# ['lily', 'rose']print(name_list)
remove( )
pop( ):删除指定下标的数据(默认为最后一个),并返回该数据
name_list = ['tom','lily','rose'] del_name = name_list.pop(0) # 返回的是被删除的元素 #结果是tom print(del_name) #结果是['lily', 'rose'] print(name_list) # 不加索引,默认删除最后一个元素 name_list.pop() # 结果是['lily'] print(name_list)
clear( ):清空列表
name_list = ['tom','lily','rose'] name_list.clear() #清除列表里面的所有元素 # 结果是[] print(name_list
2.4修改
修改指定下标数据
name_list = ['tom','lily','rose'] name_list[0]='yaoyao' name_list[2]="yaoyao" #['yaoyao', 'lily', 'rose'] print(name_list)
逆转:reverse()
name_list=['tom','lily','rose'] name_list.reverse() # ['rose', 'lily', 'tom'] print(name_list)
排序:sort()
语法 列表.sort(key=None,reverse=False)
reverse表示排序规则,reverse=True 降序,reverse=False 升序(默认)
name_list=[1,7,3,2,8] name_list.sort() # [1, 2, 3, 7, 8] print(name_list)
2.5 join关键字
将序列中的元素以指定的分隔符连接成一个新的字符串
# 使用空字符串连接 words = ['P', 'y', 't', 'h', 'o', 'n'] result = ''.join(words) print(result) # 输出: 'Python'# 使用空格连接 words = ['Hello', 'world'] result = ' '.join(words) print(result) # 输出: 'Hello world'# 使用逗号连接 fruits = ['apple', 'banana', 'cherry'] result = ', '.join(fruits) print(result) # 输出: 'apple, banana, cherry'
3.列表的循环遍历
3.1while
name_list=['tom','lily','rose']n=0while n<len(name_list):print(name_list[n])n += 1
3.2 for
name_list=['tom','lily','rose']for i in name_list:print(i)
4.列表嵌套
应用场景:要存储高三三个班级的学生名字,每个班级的学生名字为一个列表name_list = [['xiaoming','xiaohong','xiaoli'],['tom','lily','rose'],['小李','小 杨','小张']]
如何查找到数据"小李"print(name_list[2][0])
5. 列表推导式
# 生成一个列表
num_list = [value for value in range(1, 4)]
print(num_list)
# 对列表中的数据进行过滤
data_list = [1, 9, 2, 10]
new_list = [value for value in data_list if value % 2 == 0]
print(new_list)
# 字符串转列表,每个元素复制成两份
info_str = "abc"
new_str = [value * 2 for value in info_str]
print(new_str)
二、元组
1.定义元组
# 多个数据元组
t1 = (10,20,40)
# 单个数据元组
t2 = (10,)
2.元组的常见操作
但是如果元组里面有列表,修改列表里面的数据则是支持的,故自觉很重要tuple1 = (10,20,20,['lily','lucy'],40) tuple1[3][0]='tom' # 结果是(10, 20, 20, ['tom', 'lucy'], 40) print(tuple1)
按照下标查找数据
tuple1 = ('aa','bb','cc','dd') print(tuple1[0]) # aa
len() 统计元组中数据的个数
tuple1 = ('aa','bb','cc','dd') print(len(tuple1)) # 4
三、字典
1.创建
字典的特点:符号用大括号里面的数据以键值对形式出现各个键值对之间用逗号隔开
#有数据的字典
dict1 = {'name':'tom','age':20,'gender':'男'}
#空字典
dict2 = {}### 经常
dict3 = dict()
2.字典的常见操作
2.1增
dict1 ={'name':'tom','age':20,'gender':'男'}
# 结果是{'name': 'lily', 'age': 20, 'gender': '男'}
dict1['name']='lily'
print(dict1)
dict1['id']='001'
# 结果是{'name': 'lily', 'age': 20, 'gender': '男'}
print(dict1)
2.2删
dict1 ={'name':'tom','age':20,'gender':'男'}
del dict1['name']
print(dict1) #{'age': 20, 'gender': '男'}
del(dict1['age'])
print(dict1) # {'gender': '男'}
del dict1
print(dict1) # 报错:字典没有被定义
clear() 清空字典
dict1 ={'name':'tom','age':20,'gender':'男'}
dict1.clear()
print(dict1) # {}
2.3改
2.4查
key 值查找dict1 ={'name':'tom','age':20,'gender':'男'} print(dict1['name']) #tom print(dict1['id']) #报错
注意:如果当前查找的 key 存在,则返回对应的值,否则会报错。
get()
dict . get ( key , 默认值 )注意:如果当前不存在这个 key ,则会返回第二个参数自定义的默认值,如果没有第二个参数,则返回默认的Nonedict1 ={'name':'tom','age':20,'gender':'男'} print(dict1.get('name')) # tom print(dict1.get('id', '不存在')) # 不存在
3.字典的遍历循环
3.1遍历字典的key
dict = {'name':'tom','age':20,'gender':'男'}
for k in dict.keys():
print(k)
3.2遍历字典的value
dict = {'name':'tom','age':20,'gender':'男'}
for v in dict.values():
print(v)
3.3遍历字典的元素
dict = {'name':'tom','age':20,'gender':'男'}
for items in dict.iitems()
print(items)
3.4遍历字典的键值对
dict = {'name':'tom','age':20,'gender':'男'}
for k,v in dict.items():
print(k,v)