python中for循环的用法

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法模式:for iterating_var in sequence:

in 字面意思,从某个集合(列表等)里顺次取值

#遍历数字序列
the_count=[1,2,3,4,5]
for number in the_count:
    print(f"This is count {number}")
输出结果:

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5 

#遍历一维字符串数组
fruits=['apples','oranges','dimes','quarters']
for fruit in fruits:
    print(f"A fruit of type:{fruit}")

输出结果为:

A fruit of type:apples
A fruit of type:oranges
A fruit of type:dimes
A fruit of type:quarters

#遍历字符串
list_python='python'
for j in list_python:
    print(f"{j}")
输出结果为:

p
y
t
h
o
n


#通过序列索引迭代
elements=[]#列表为空
for i in range(0,6):#012345
print(f"Adding {i} to the list.")

elements.append(i)#得到elements=[0,1,2,3,4,5]

#len(elements)长为6,range(len(elements))==range(6)
for i in range(len(elements)):
print(f"Elemnet was:{i}")

输出结果为:

Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Elemnet was:0
Elemnet was:1
Elemnet was:2
Elemnet was:3
Elemnet was:4
Elemnet was:5

 

转载于:https://www.cnblogs.com/foremostxl/p/9375785.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值