学习目标:
- python基础语法
学习内容:
4.1.4 列表应用 :取出列表内的偶数
list = [1,2,3,4,5,6,7,8,9,10]
mylist = []
def list_while():
index = 0
while index < len(list):
element = list[index]
print(f"遍历结果为:{element}")
if element %2 ==0:
mylist.append(element)
index += 1
else:
index += 1
def list_for():
for element in list:
print(f"遍历结果为{element}")
if element %2 ==0:
mylist.append(element)
list_while()
print(mylist)
list_for()
print(mylist)
4.2 元组 tuple 不可修改
应用前提:定义完成后不可被修改
定义:变量=tuple(元素,元素) 变量=元组名(元素,元素) 元组名=()
语法同list一样
4.2.1 操作
1.index() 查找元素 返回其下标
2.count() 计算元素出现次数
3.len(元组) 统计元组元素个数
list内部元素可改变,tuple不可变,嵌套后同样符合
tuple可容纳多个数据,且有序存储,允许重复,不可以修改,支持for循坏,支持嵌套
tuple=('周杰伦',11,['football','music'])
index=tuple.index(11)
print(f"{tuple[index]}")
print(tuple[0])
del tuple[2][0]
tuple[2].insert(1,'coding') # 注意
print(tuple)
4.3 字符串 str 不可以修改
4.3.1 操作
1.查找 str.index('字符串')
2.替换 str.replace(' 字符串1 ',' 字符串2 ')
3.分割 str.split(分割符)分割后变为list
4.strip 去除首尾字符 strip("字符串")
5.计数 count 统计字符出现的次数 str.count("字符串")
6.长度 统计字符串长度 len(str)
str="I want to eat an apple,but i am not hungry"
x=str.index("want")
print(f"want的起始下标为{x}")
value1=str[2]
value2=str[-5]
print(f"{value1},{value2}")
new_str=str.replace('a','A') # 替换
print(f"替换后为{new_str}")
new_str2=str.split(" ") # 按照空格来切分str
print(f"切割后为{new_str2},类型是{type(new_str2)}")
str=" 12I want to eat an apple,but i am not hungry21 "
new_str=str.strip()
print(new_str)
new_str2=new_str.strip(('12'))
print(new_str2)
count=str.count('a')
print(f"a出现的次数为{count}")
len=len(new_str2)
print(f"{len}")
4.4 序列 可修改
4.4.1 操作
1.切片 序列[起始下标:结束下标:步长]
起始下标:可空,默认为从头开始
结束下标:切片时不包含结束下标字符串,可空,默认末尾结束
步长:可控,默认为1 负数为从末尾开始,反向取
str='0123456789'
new_str=str[::2] # 从头到尾 隔一个取一个切片
print(new_str)
new_str2=str[8::-2] # 从末尾到开头 隔一个取一个切片
print(new_str2)
new_str3=str[3:8:2] # 从3到8 隔一个取一个切片
print(new_str3)
举例:
str="万过薪月,员序程马黑来,nohtyp学"
# 先倒序再切片
new_str1=str[::-1][9:14]
print(new_str1)
# 先切片再倒序
new_str2=str[5:10][::-1]
print(new_str2)
# split分割 去掉"来" 再倒序
new_str3=str.split(",")[1].replace("来","")[::-1]
print(new_str3)
4.5 集合
列表【】可修改,支持元素重复且有序
元组() 字符串" "不可修改,支持元素重复且有序
集合 { } 无序且元素不重复 可修改 空集合 set()
4.5.1 集合的操作
1.添加 set.add()
2.移除 set.remove()
3.随机取 set.pop() 取完后集合会被修改
4.清空 set.clear()
5.差集 set1.difference(set2) 取出集合1有的而集合2没有的差集
6.消除差集 set1.difference_update(set2) 在集合1中,删除和集合2相同的元素 无返回值
7.合并 set1.union(set2)
8.统计 len(set) 集合内的元素数量 集合自动去重
9.遍历 支持for循环 无序不支持while
set1={ "Hello World","世界你好",1,2,3}
set2={ "世界你好","且听风吟",2,3,4}
new_set=set2.difference(set1) # 输出差集
print(new_set)
set1.difference_update(set2) # 消除差集
print(set1)
print(set1.union(set2)) # 合并
学习产出:
- CSDN 技术博客 1 篇