溫馨提示×

python里的for in循環(huán)如何寫

小億
100
2024-01-23 11:24:01
欄目: 編程語言

在Python中,使用for-in循環(huán)的基本語法是:

for 變量 in 可迭代對象:
    # 循環(huán)體代碼

其中,可迭代對象是一個序列(如列表、元組、字符串)或者一個可迭代的對象(如字典、集合),變量是每次循環(huán)時取出的值。

以下是幾個for-in循環(huán)的示例:

  1. 遍歷列表:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  1. 遍歷字符串:
text = "Hello"
for letter in text:
    print(letter)
  1. 遍歷字典的鍵:
person = {"name": "Alice", "age": 25}
for key in person:
    print(key)
  1. 遍歷字典的值:
person = {"name": "Alice", "age": 25}
for value in person.values():
    print(value)
  1. 遍歷字典的鍵值對:
person = {"name": "Alice", "age": 25}
for key, value in person.items():
    print(key, value)

希望這些示例能幫助你理解如何在Python中使用for-in循環(huán)。

0