约 975 字

约 5 分钟

#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.

调用字典的 items 方法可以获得键值对的列表:

score_list:dict[str,int] = {
    'Tom': 88,
    'Jerry': 99,
    'Spike': 66
}
for key,value in score_list.items():    # 这里使用了下一篇的解包语法
    print(key, value)

>>> 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/12/2

作者: PlanC

创建: 2025/4/10