在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)
這些方法可以根據具體的需求選擇使用。