python 字段遍历
时间: 2023-08-30 21:11:24 浏览: 80
在 Python 中,可以使用 `for` 循环语句来遍历一个列表、元组、字典等数据结构中的元素。下面是一些示例:
1. 遍历列表:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
输出:
```
apple
banana
cherry
```
2. 遍历元组:
```python
numbers = (1, 2, 3)
for num in numbers:
print(num)
```
输出:
```
1
2
3
```
3. 遍历字典的键:
```python
person = {"name": "Alice", "age": 25, "location": "New York"}
for key in person:
print(key)
```
输出:
```
name
age
location
```
4. 遍历字典的值:
```python
person = {"name": "Alice", "age": 25, "location": "New York"}
for value in person.values():
print(value)
```
输出:
```
Alice
25
New York
```
5. 遍历字典的键值对:
```python
person = {"name": "Alice", "age": 25, "location": "New York"}
for key, value in person.items():
print(key, value)
```
输出:
```
name Alice
age 25
location New York
```
阅读全文