Python中的for语句可以用于遍历任何可迭代对象,包括但不限于列表、元组、集合、字典等。
以下是一些示例:
- 遍历列表:
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)
输出:
apple banana cherry
- 遍历集合:
fruits = {'apple', 'banana', 'cherry'} for fruit in fruits: print(fruit)
输出:
apple banana cherry
- 遍历元组:
fruits = ('apple', 'banana', 'cherry') for fruit in fruits: print(fruit)
输出:
apple banana cherry
- 遍历字典的键:
fruits = {'apple': 1, 'banana': 2, 'cherry': 3} for fruit in fruits: print(fruit)
输出:
apple banana cherry
- 遍历字典的值:
fruits = {'apple': 1, 'banana': 2, 'cherry': 3} for fruit in fruits.values(): print(fruit)
输出:
1 2 3
- 遍历字典的键值对:
fruits = {'apple': 1, 'banana': 2, 'cherry': 3} for fruit, quantity in fruits.items(): print(fruit, quantity)
输出:
apple 1 banana 2 cherry 3
总之,for语句可以用于遍历各种可迭代对象,不仅仅局限于列表。