一、Python遍歷
在編程中,遍歷是一個重要而且常見的操作,即逐個訪問某個數據結構中的元素。在Python中,我們可以通過for循環來遍歷一個數據結構,如list、字元串等。
二、Python遍歷list
lst = [1, 2, 3, 4, 5]
for ele in lst:
print(ele)
運行結果:
1
2
3
4
5
上面的代碼使用for循環遍歷了一個list,並且列印出了每個元素的值。
三、Python遍歷列表
lst = ["apple", "banana", "orange"]
for ele in lst:
print(ele)
運行結果:
apple
banana
orange
上面的代碼使用for循環遍歷了一個字元串列表,並且列印出了每個元素的值。
四、Python遍歷求和
lst = [1, 2, 3, 4, 5]
sum = 0
for ele in lst:
sum += ele
print(sum)
運行結果:
15
上面的代碼使用for循環遍歷了一個list,並且求出了list中所有元素的和。
五、Python遍歷txt
with open("file.txt", "r") as f:
for line in f:
print(line)
上面的代碼使用for循環遍歷了一個txt文件,並且列印出了每一行的內容。
六、Python遍歷圖片
from PIL import Image
img = Image.open("image.jpg")
width, height = img.size
for x in range(width):
for y in range(height):
print(img.getpixel((x, y)))
上面的代碼使用for循環遍歷了一張圖片,並且列印出了每個像素點的RGB值。
七、Python遍歷循環
lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i])
上面的代碼使用for循環遍歷了一個list,並且列印出了每個元素的值。
八、Python遍歷100
for i in range(1, 101):
print(i)
上面的代碼使用for循環遍歷了1到100這100個數字,並且列印出了每個數字的值。
九、Python遍歷文件內容
with open("file.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line)
上面的代碼使用for循環遍歷了一個txt文件中的所有內容,並且列印每一行的內容。
以上就是Python遍歷map完全指南,通過上面的例子,你可以掌握如何使用for循環遍歷不同類型的數據結構。希望這篇文章對你有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/243643.html