769

4 分钟

#Python 的容器迭代

元组、列表、字典和集合,都是可迭代对象,可以通过 for 循环依次读取元素:

#元组

元组依次取得元素:

students:tuple[str, str, str] = ("Tom", "Jerry", "Spike") for student in students: print(student)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#列表

列表依次取得元素:

students:list[str] = ["Tom", "Jerry", "Spike"] for student in students: print(student)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#字典

字典依次取得 索引

score_list:dict[str,int] = { 'Tom': 88, 'Jerry': 99, 'Spike': 66 } for key in score_list: print(key, score_list[key])

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#集合

元组依次取得元素:

fruits:set[str] = {'Apple', 'Orange', 'Strawberry', 'Banana', 'Pineapple'} for fruit in fruits: print(fruit)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#字符串

字符串也是可迭代对象,依次取得字符:

text:str = "hello world" for word in text: print(word)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

创建于 2025/4/10

更新于 2025/5/21