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)
```
以上是一些常用的遍歷函數寫法,具體可以根據需要進行修改和擴展。