【发布时间】:2018-02-19 00:09:41
【问题描述】:
我试过这个:
myList = [range(1,10)]
print(myList)
得到这个输出:
range(1, 10)
为什么它没有返回列表 [1,2,3,4,5,6,7,8,9]?
【问题讨论】:
-
注意,格式化代码,缩进四个空格。
标签: python python-3.x
我试过这个:
myList = [range(1,10)]
print(myList)
得到这个输出:
range(1, 10)
为什么它没有返回列表 [1,2,3,4,5,6,7,8,9]?
【问题讨论】:
标签: python python-3.x
您正在 Python3 中运行该示例,其中 range 函数返回一个可迭代对象。因此,您必须将生成器传递给list 函数以强制表达式给出完整列表:
l = list(range(10))
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用生成器,您可以像这样迭代它:
for i in function_that_yields_generator():
#do something
您还可以使用函数next() 从生成器中获取元素。由于 range 函数是可迭代的而不是迭代器,因此您可以使用:
l = range(10)
new_l = iter(l)
>>next(new_l)
0
>>next(new_l)
1
>>next(new_l)
2
等等。
对于迭代器,您可以这样做:
>>s = function_that_yields_generator()
>>next(s)
#someval1
>>next(s)
#someval2
【讨论】: