关于Python的Yield,无法获取数据



 def test1():
    for i in range(1,100):
        yield i;
print test1();

没有预想的输出1-100 。输出的是 <generator object test1 at 0x02A9FE68>
怎么获取?

python generator

Nikusyo 10 years, 2 months ago

对于yield的理解,stackoverflow上有类似提问: What does the yield keyword do in Python ?,中文翻译: python关键字yield的详解

阿萨德却无法 answered 10 years, 2 months ago

generator是生成器,用yield表达式的时候是只有在实际需要的时候才取值回来,


 >>> t = test1()
>>> t.next()
1
>>> t.next()
2
>>>

它不会一下把1-100全输出。

不清楚你要输出什么样的格式。


 >>> print [i for i in range(1, 100)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

节操即零食 answered 10 years, 2 months ago

调用test1返回的是一个generator, 你可以试一下:


 generator = test1()
for i in generator:
    print i

或者:
print generator.next()

坦桑尼亚造船厂 answered 10 years, 2 months ago

Your Answer