def reverse(data): for i in range(len(data)-1, -1, -1): yield data[i] for char in reverse('Hello'): print(char)
时间: 2024-03-28 17:39:51 浏览: 20
这段代码是 Python 中的一个生成器函数,用于将一个字符串反向输出。具体来说,它定义了一个名为 reverse 的函数,该函数接受一个参数 data,表示要反向输出的字符串。在函数体内,使用 for 循环从字符串末尾开始,依次取出每个字符,然后使用 yield 语句将其作为生成器的输出返回。这样,当该函数被调用时,它会返回一个生成器对象,可以使用 for 循环遍历该对象并输出每个字符,从而实现字符串的反向输出。
在代码的后面部分,通过调用 reverse('Hello') 得到一个生成器对象,然后使用 for 循环遍历该对象并输出每个字符。由于生成器函数是惰性求值的,因此只有在需要时才会生成下一个字符,从而实现了更加高效的字符串反向输出。输出结果为:
o
l
l
e
H
相关问题
-1 for i in range()
The statement "-1 for i in range()" is not a valid Python statement.
To use the "range()" function to loop through a sequence in reverse order, we need to specify the start and end values and a step of -1.
For example, to print the numbers from 10 to 1 in reverse order, we can use:
for i in range(10, 0, -1):
print(i)
This will output:
10
9
8
7
6
5
4
3
2
1
for i in range(len(str1)-1,-1,-1):
This code creates a loop that iterates through the string 'str1' backwards, starting from the last index (len(str1)-1) and going up to index 0, with a step of -1.
Essentially, it is iterating through the characters of 'str1' in reverse order.