在Python中,有几种方法可以遍历函数:
def my_function():
for i in range(5):
yield i
for item in my_function():
print(item)
def my_function(n):
if n > 0:
my_function(n-1)
print(n)
my_function(5)
def square(x):
return x**2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
for item in squared_numbers:
print(item)
def square(x):
return x**2
numbers = [1, 2, 3, 4, 5]
squared_numbers = (square(x) for x in numbers)
for item in squared_numbers:
print(item)
这些方法可以根据具体的需求选择使用。