[英]Python function or syntactic sugar to return all elements of a generator expression?
Given a generator expression, I would like to make a single function call that returns all elements of the generator expression. 给定生成器表达式,我想进行一个函数调用,该函数返回生成器表达式的所有元素。
>>> a = (i for i in range(1,101))
>>> a
<generator object <genexpr> at 0x101873460>
>>> a.next()
1
>>> a.next()
2
In other words, I would like to avoid loops like: 换句话说,我想避免像这样的循环:
for i in a:
print i
and instead have a syntactic sugar for the loop: 而是为循环添加语法糖:
a.all() # or the like
I looked at itertools but it wasn't clear to me that such a thing exists. 我看着itertools,但我不清楚是否存在这样的东西。
You can just create a list out of it as: 您可以按照以下方式创建一个列表:
list(a)
a = (i for i in range(1,101))
print list(a)
[1, 2, 3, ..., 100]
Infact, since in this case you are getting the items into a list, you can also use list comprehension: 实际上,由于在这种情况下将项目放入列表中,因此您还可以使用列表理解:
a = list(range(1, 101))
Now, a
is a list instead of a generator object. 现在, a
是列表而不是生成器对象。
I think it is the best solution. 我认为这是最好的解决方案。
a = [i for i in range(1, 101)]
print a
[1, 2, 3, ..., 100]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.