python入门基础,关于for循环学习,看这一篇就够了

前言

  for循环是在python开发中用的很多的一种循环类型, 需要熟练掌握。

for循环的使用场景

  • for循环用于重复执行具体次数操作
  • for循环主要用来遍历、循环、列表、集合、字典,文件、甚至是自定义类或函数。

for循环操作列表实例演示

  • 使用for循环经常结合if语句使用,对列表进行遍历元素、修改元素、删除元素、统计列表中元素的个数。
for循环用来遍历整个列表
#for循环主要用来遍历、循环、序列、集合、字典
Fruits = ['apple','orange','banana','grape']

for fruit in Fruits:
    print(fruit)
print("结束遍历")
结果演示:
    apple
    orange
    banana
    grape
    结速遍历
for循环用来修改列表中的元素
#for循环主要用来遍历、循环、序列、集合、字典
#把banana改为Apple
Fruits=['apple','orange','banana','grape']
for i in range(len(Fruits)):
    if Fruits[i] == 'banana':
        Fruits[i] ='apple'
print(Fruits)
结果演示:['apple', 'orange', 'apple', 'grape']
  1. for循环用来删除列表中的元素
Fruits=['apple','orange','banana','grape']
for i in  Fruits:
    if i == 'banana':
        Fruits.remove(i)
print(Fruits)
结果演示:['apple', 'orange', 'grape']

如果对软件测试、接口测试、自动化测试、持续集成、面试经验。感兴趣可以进到902061117,群内会有不定期的分享测试资料。还会有技术大牛,业内同行一起交流技术

for循环统计列表中某一元素的个数
#统计apple的个数
Fruits = ['apple','orange','banana','grape','apple']
count = 0
for i in  Fruits:
    if i=='apple':
        count+=1
print("Fruits列表中apple的个数="+str(count)+"个")
结果演示:Fruits列表中apple的个数=2个

注:列表某一数据统计还可以使用Fruit.count(object)
for循环实现1到9相乘
sum=1
for i in list(range(1,10)):
    sum *= i
print("1*2...*9=" + str(sum))
结果演示:1*2...*10=362880
遍历字符串
for str in 'abc':
    print(str)

结果演示:
a
b
c
遍历集合对象
for str in {'a',2,'bc'}:
    print(str)

结果演示:
a
2
bc
遍历文件
for content in open("D:\\test.txt"):
    print(content)

结果演示:
朝辞白帝彩云间,千里江陵一日还。
两岸猿声啼不住,轻舟已过万重山。
遍历字典
for key,value in {"name":'码上开始',"age":22}.items():
    print("键---"+key)
    print("值---"+str(value))

结果演示:
键---name
值---码上开始
键---age
值---22

如果对软件测试、接口测试、自动化测试、持续集成、面试经验。感兴趣可以进到902061117,群内会有不定期的分享测试资料。还会有技术大牛,业内同行一起交流技术

猜你喜欢

转载自blog.csdn.net/laozhu_Python/article/details/107866157
今日推荐