Python 为什么变量的显式定义可以用来调用函数,而迭代器却不能?
此python脚本返回值Python 为什么变量的显式定义可以用来调用函数,而迭代器却不能?,python,iterator,generator,Python,Iterator,Generator,此python脚本返回值90.0: import itertools a=[12,345,1423,65,234] b=[234,12,34,1,1,1] c=[1,2,3,4] def TestFunction (a, b, c): result = a + b/c return result Params=itertools.product(a, b, c) x = 2 print(TestFunction(*list(Params)[x])) 但是,我想对x范围内
90.0
:
import itertools
a=[12,345,1423,65,234]
b=[234,12,34,1,1,1]
c=[1,2,3,4]
def TestFunction (a, b, c):
result = a + b/c
return result
Params=itertools.product(a, b, c)
x = 2
print(TestFunction(*list(Params)[x]))
但是,我想对x范围内的函数进行评估,如下所示:
for x in range (5):
print(TestFunction(*list(Params)[x]))
我希望它返回一系列值:246.0
,129.0
,90.0
,70.5
,14.0
;然而,我得到:
“索引器:列表索引超出范围。”
为什么函数在明确定义x
时求值,而不是在它是迭代器时求值
for x in range (5):
print(TestFunction(*list(Params)[x]))
Params
是一个迭代器。第一次通过循环时,您完全通过将其转换为列表来使用它。因此,在第二次迭代中,它没有任何内容,将其转换为一个列表将产生一个空列表[]
,并且尝试获取该列表的索引1将不起作用
相反,将迭代器转换为循环外的列表
params = list(Params)
for x in range(5):
print(TestFunction(*params[x]))
因为在迭代器上调用list()
会耗尽迭代器。因此,只能调用一次:
>>> Params=itertools.product(a, b, c)
>>> Params
<itertools.product object at 0x7f5ed3da5870>
>>> list(Params)
[(12, 234, 1), (12, 234, 2)..., (234, 1, 4)]
>>> list(Params)
[]
然后根据需要访问它,通过下标访问任意项
如果要按照for循环的示例顺序访问这些项,只需在迭代器上调用next()
:
for i in range(5):
print(TestFunction(*next(Params)))
因为
Params
是一个迭代器,将其转换为列表会完全消耗它
有两种方法可以处理您的案例:
Params = list(itertools.product(a, b, c))
复制。复制:
from copy import copy
print(TestFunction(*list(copy(Params))[x]))
大多数情况下,方法1是合适的。偶尔你可能会想要方法2。啊,这就解释了我在试图弄明白这一点时得到的空列表。非常感谢你。
from copy import copy
print(TestFunction(*list(copy(Params))[x]))