def f(a):
for i in a:
print i
>>> f(i for i in [1,2,3])
1
2
3
>>> f([i for i in [1,2,3]])
1
2
3
>>> f((i for i in (1,)))
1
我在第一个示例中传递了元组或列表吗?
它们之间有什么区别?
最佳答案
您传递一个生成器和一个列表:
>>> def f(a):
... print type(a)
... for i in a:
... print i
...
>>> f(i for i in [1,2,3])
<type 'generator'>
1
2
3
>>>
>>> f([i for i in [1,2,3]])
<type 'list'>
1
2
3
>>> f((i for i in (1,)))
<type 'generator'>
1
>>>
两者都可以在 for 循环中迭代,但工作方式不同。生成器每次迭代都会执行一条语句,列表(或另一个 Iterables)是一段数据,它的所有元素都存在,无需任何操作。
有关发电机的更多信息 here
关于python - 实际上作为参数传递给函数的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25616647/