在Python中,迭代脚本编程程序主要使用`for`循环和`while`循环两种方式。
for循环 Python中的`for`循环用于遍历序列(如列表、元组、字符串)或其他可迭代对象。其基本语法如下:
```python
for variable in iterable:
循环体,每次循环执行这里
```
`variable`:每次循环时当前元素的值。
`iterable`:可迭代对象,如列表、元组、字符串、字典、文件对象等。
示例
```python
遍历列表
permanent = ['李晨', '郑凯', '沙溢', '白鹿', '周琛', '范丞丞', '宋雨琦', '张真源']
for per in permanent:
print(per)
遍历元组
numbers = (1, 2, 3, 4, 5)
for num in numbers:
print(num * 2)
遍历字符串
for char in "abcd":
print(char * 2)
```
while循环
`while`循环通过一个条件来控制循环的执行。当条件为真时,循环继续执行;当条件为假时,循环结束。其基本语法如下:
```python
while condition:
循环体,只要条件为真,就执行这里
```
`condition`:循环继续执行的条件。
示例 ```python i = 0 while i < 5: print(i) i += 1 ```迭代器
Python中的迭代器是一个可以记住遍历的位置的对象。迭代器对象必须实现两个方法:`__iter__()`和`__next__()`。`__iter__()`方法返回迭代器对象本身,`__next__()`方法返回容器的下一个值。当容器中没有更多元素时,`__next__()`方法会抛出`StopIteration`异常。
示例 ```python 使用iter和next实现迭代 my_list = [1, 2, 3, 4, 5] my_iterator = iter(my_list) while True: try: print(next(my_iterator)) except StopIteration: break ```内置函数
Python标准库中的`itertools`模块提供了许多用于创建迭代器的函数,如`count`、`cycle`、`repeat`、`combinations`、`permutations`和`product`等。
示例
```python
from itertools import count, cycle, repeat
无限计数器
counter = count(start=1)
for i in range(3):
print(next(counter)) 输出: 1, 2, 3
循环迭代
colors = cycle(['red', 'green', 'blue'])
for i in range(4):
print(next(colors)) 输出: red, green, blue, red
重复元素
repeater = repeat('hello', 3)
for item in repeater:
print(item) 输出: hello, hello, hello
```
通过以上方法,你可以有效地迭代脚本编程程序,遍历各种数据结构,并在需要时创建和使用迭代器。