Python中遍历函数的写法可以有多种,具体取决于遍历的对象和需要执行的操作。以下是一些常用的遍历函数写法:
1. 遍历列表:
```python
my_list = [1, 2, 3, 4, 5]
# for循环遍历
for item in my_list:
print(item)
# while循环遍历
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
# map函数遍历并执行操作
new_list = list(map(lambda x: x * 2, my_list))
print(new_list)
```
2. 遍历字典:
```python
my_dict = {'a': 1, 'b': 2, 'c': 3}
# 遍历key
for key in my_dict:
print(key)
# 遍历value
for value in my_dict.values():
print(value)
# 遍历key-value对
for key, value in my_dict.items():
print(key, value)
```
3. 遍历字符串:
```python
my_str = 'hello world'
# for循环遍历
for char in my_str:
print(char)
# while循环遍历
i = 0
while i < len(my_str):
print(my_str[i])
i += 1
```
4. 遍历文件:
```python
# 打开文件
with open('my_file.txt', 'r') as f:
# for循环遍历每一行
for line in f:
print(line)
# 或者使用readlines()方法获取所有行并遍历
lines = f.readlines()
for line in lines:
print(line)
```
以上是一些常用的遍历函数写法,具体可以根据需要进行修改和扩展。