温馨提示×

python里的for in循环如何写

小亿
138
2024-01-23 11:24:01
栏目: 编程语言

在Python中,使用for-in循环的基本语法是:

for 变量 in 可迭代对象: # 循环体代码 

其中,可迭代对象是一个序列(如列表、元组、字符串)或者一个可迭代的对象(如字典、集合),变量是每次循环时取出的值。

以下是几个for-in循环的示例:

  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循环。

0