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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM