共計 438 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 中有多種方式可以循環遍歷列表,下面是三種常用的方法:
- 使用 for 循環:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
輸出:
1
2
3
4
5
- 使用 while 循環和索引:
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
輸出:
1
2
3
4
5
- 使用 enumerate 函數同時獲取索引和值:
my_list = [1, 2, 3, 4, 5]
for index, item in enumerate(my_list):
print(f"Index: {index}, Value: {item}")
輸出:
Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5
以上是 Python 中常用的循環遍歷列表的方法,根據實際需求選擇適合的方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完