什么是“发电机对象"?在django? [英] What is "generator object" in django?

查看:46
本文介绍了什么是“发电机对象"?在django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django投票程序包,当我在外壳中使用方法get_top()时,它返回类似生成器对象位于0x022f7AD0 之类的内容,我以前从未见过类似的东西,怎么办您访问它是什么?

Am using Django voting package and when i use the method get_top() in the shell, it returns something like "generator object at 0x022f7AD0, i've never seen anything like this before, how do you access it and what is it?

我的代码:

v=Vote.objects.get_top(myModel, limit=10, reversed=False)
print v
<generator object at 0x022f7AD0>

注意:我以为 get_top 会返回一个很好的myModel列表,我可以执行 v.name

NB: I thought get_top will just return a nice list of myModel, which i can do something like v.name etc

推荐答案

如果需要列表,只需在生成器对象上调用list().

If you want a list, just call list() on your generator object.

python中的生成器对象有点像惰性列表.仅当您遍历元素时才对它们进行评估. (因此,呼叫清单将对所有呼叫者进行评估.)

A generator object in python is something like a lazy list. The elements are only evaluated as soon as you iterate over them. (Thus calling list on it evaluates all of them.)

例如,您可以这样做:

>>> def f(x):
...  print "yay!"
...  return 2 * x
>>> g = (f(i) for i in xrange(3))    # generator comprehension syntax
>>> g
<generator object <genexpr> at 0x37b6c0>

>>> for j in g: print j
... 
yay!
0
yay!
2
yay!
4

仅在迭代f时查看如何评估f.您可以在此处找到有关该主题的出色材料: http://www.dabeaz.com/generators/

See how f is evaluated only as you iterate over it. You can find excellent material on the topic here: http://www.dabeaz.com/generators/

这篇关于什么是“发电机对象"?在django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆