python第六章 LIST的遍历

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}")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值