遍歷就是從頭到尾依次從串列中獲取資料,在回圈體內部針對每一個元素,執行相同的操作,
在Python中為了提高串列的遍歷效率,專門提供的迭代(iteration)遍歷,
使用 for...in 就能夠在 Python 中實作迭代遍歷,
在 Python 中,for 回圈可以遍歷任何序列的專案,如串列、元組、字典以及字串,
本文只用串列作簡單舉例,涉及到個別資料型別的特殊用法,我們后面再補充,
for...in 回圈流程圖

for基礎用法
語法格式:
# for 回圈內部使用的變數 in 串列
for name in name_list:
回圈內部針對串列元素進行操作
print(name)
盡管 Python 的串列中可以存盤不同型別的資料,但是在開發中,更多的應用場景是用串列存盤相同型別的資料,
通過迭代遍歷,在回圈體內部,針對串列中的每一項元素,執行相同的操作,
實體
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print("當前水果 : %s" % fruit)
#當前水果 : banana
#當前水果 : apple
#當前水果 : mango
我們也通過序列索引來進行迭代回圈,
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print('當前水果 : %s' % fruits[index])
#當前水果 : banana
#當前水果 : apple
#當前水果 : mango
我們使用了內置函式 len() 和 range(),
函式 len() 回傳串列的長度,即元素的個數,
函式 range() 回傳一個序列的數,用于生成一系列連續整數,多用于 for 回圈中,
回圈使用 else 陳述句
else 中的陳述句會在回圈正常執行完的情況下執行,即 for回圈不是通過 break 跳出而中斷的,while … else 也是一樣,
實體
# 迭代 10 到 20 之間的數字
for num in range(10, 20):
# 根據因子迭代
for i in range(2, num):
if num % i == 0:
j = num/i
print('%d 等于 %d * %d' % (num, i, j))
break
# 回圈的 else 部分
else:
print('%d是一個質數' % num)
結果
10 等于 2 * 5
11是一個質數
12 等于 2 * 6
13是一個質數
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17是一個質數
18 等于 2 * 9
19是一個質數

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/56987.html
標籤:Python
上一篇:130被圍繞的區域
