LIST的遍历
while遍历
while 可以自定循环条件
def list_while_func():
mylist = ["张三","李四","王麻子"]
index = 0
while index<len(mylist):###小于列表元素长度
element = mylist[index]###
print(f"列表元素为:{element}")
index+=1
list_while_func()
for遍历
for 不能自定循环条件
def list_for_func():
mylist= ["张三","李四","王麻子"]
for index in mylist:
print(f"列表元素有{index}")
list_for_func()
案例:
while 循环写法
mylist = [1,2,3,4,5,6,7,8,9,10]
newlist = []
index = 0
while index<len(mylist):##下标索引值 小于元素个数0
element = mylist[index]
index+=1
if element % 2 ==0:
newlist.append(element)
print(f"组成新列表为{newlist}")
for 循环写法
mylist = [1,2,3,4,5,6,7,8,9,10]
newlist = []
index = 0
for element in mylist:
if element % 2 == 0:
newlist.append(element)
print(f"组成新列表为{newlist}")
元组的定义和操作:
定义元组使用小括号,定义单个元组,必须在括号后加上一个逗号
t1 = ("hello",)
print(f"元组t1的类型是{type(t1)},元组t1的内容是{t1}")
元组虽然不能修改 但是在元组内嵌套的list 可以修改
案例
t1 = ("周杰伦",11,["football","music"])
location = t1.index(11)
print(f"年龄所在元组下标位置为{location}")
name = t1[0]
print(f"姓名为{name}")
hobby = t1[2]
hobby.remove("football")
print(f"学生现存爱好为{hobby}")
hobby.append("coding")
print(f"学生最新的爱好为{hobby}")
字符串:也是数据容器的一员
数据容器字符串
字符串下标索引跟 列表一样 不可修改
replace
old_str = "wangxiaolong niubi 666"
new_str = old_str.replace("wangxiaolong","冯海瑞")
print(f"修改前的字符串为{old_str},修改后的新字符串为{new_str}")
split可以按照指定内容对字符串进行拆分,拆分为列表格式
old_str = "wangxiaolong niubi 666"
new_str = old_str.split(" ")
print(f"拆分前的字符串为{old_str},拆分后后的新字符串为{new_str}")###
strip去除指定字符串
不传入参数就是除去首尾空格
count 统计字符串出现次数
len统计字符串长度
总结
案例
old_str = "itheima itcast boxuegu"
num1 = old_str.count("it")
print(f"it字符个数为{num1}")
new_str = old_str.replace(" ","|")
print(f"替换后的字符串为{new_str}")
changestr = new_str.split("|")
print(f"新修改后的列表为{changestr}")