首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python for循环的使用(三)

Python for循环的使用(三)

作者头像
py3study
发布2020-01-06 18:43:37
8930
发布2020-01-06 18:43:37
举报
文章被收录于专栏:python3python3

Python for循环的使用

(一)for循环的使用场景

1.如果我们想要某件事情重复执行具体次数的时候可以使用for循环。 2.for循环主要用来遍历、循环、序列、集合、字典,文件、甚至是自定义类或函数。

(二)for循环操作列表实例演示

  1. 使用for循环对列表进行遍历元素、修改元素、删除元素、统计列表中元素的个数。

1.for循环用来遍历整个列表

#for循环主要用来遍历、循环、序列、集合、字典
Fruits=['apple','orange','banana','grape']
for fruit in Fruits:
    print(fruit)
print("结束遍历")
结果演示:
    apple
    orange
    banana
    grape

2.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']

3.for循环用来删除列表中的元素

Fruits=['apple','orange','banana','grape']
for i in  Fruits:
    if i=='banana':
        Fruits.remove(i)
print(Fruits)
结果演示:['apple', 'orange', 'grape']

4.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)

5.for循环实现1到9相乘

sum=1
for i in list(range(1,10)):
    sum*=i
print("1*2...*10="+str(sum))
结果演示:1*2...*10=362880

6.遍历字符串

for str in 'abc':
    print(str)
结果演示:
a
b
c

7.遍历集合对象

for str in {'a',2,'bc'}:
    print(str)
结果演示:
a
2
bc

8.遍历文件

for content in open("D:\\test.txt"):
    print(content)
结果演示:
朝辞白帝彩云间,千里江陵一日还。

两岸猿声啼不住,轻舟已过万重山。

9.遍历字典

for key,value in {"name":'Kaina',"age":22}.items():
    print("键---"+key)
    print("值---"+str(value))
结果演示:
键---name
值---Kaina
键---age
值---22
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python for循环的使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档