Python中循环遍历
时间: 2024-02-09 17:06:46 浏览: 89
Python中循环遍历有多种方式,比较常用的方式有for循环和while循环。下面是两种方式的示例:
1. for循环:
```python
# 遍历列表
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
# 遍历字典
my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
for key, value in my_dict.items():
print(key, value)
# 遍历字符串
my_str = 'hello world'
for char in my_str:
print(char)
```
2. while循环:
```python
# 遍历列表
my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
# 遍历字典
my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
keys = list(my_dict.keys())
i = 0
while i < len(keys):
key = keys[i]
value = my_dict[key]
print(key, value)
i += 1
# 遍历字符串
my_str = 'hello world'
i = 0
while i < len(my_str):
print(my_str[i])
i += 1
```
阅读全文