共計 335 個字符,預計需要花費 1 分鐘才能閱讀完成。
在 Python 中,可以使用 for 循環來遍歷元組。以下是幾種常見的遍歷元組的方法:
- 使用 for 循環遍歷元組的每個元素:
my_tuple = (1, 2, 3, 4, 5)
for item in my_tuple:
print(item)
- 使用 range() 函數和 len() 函數結合遍歷元組的索引:
my_tuple = (1, 2, 3, 4, 5)
for i in range(len(my_tuple)):
print(my_tuple[i])
- 使用 enumerate() 函數遍歷元組的索引和元素:
my_tuple = (1, 2, 3, 4, 5)
for index, item in enumerate(my_tuple):
print(index, item)
這些方法可以根據需求選擇適合的遍歷方式。
丸趣 TV 網 – 提供最優質的資源集合!
正文完