简体   繁体   English

Python函数或语法糖返回生成器表达式的所有元素?

[英]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)

Example

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.

相关问题 列表推导式是 Python 3 中`list(generator expression)` 的语法糖吗? - Are list comprehensions syntactic sugar for `list(generator expression)` in Python 3? Python语法糖:函数arg别名 - Python syntactic sugar: function arg aliases Python function 工具提示的所有句法元素是什么? - What are all the syntactic elements of a Python function tooltip? 如何在没有语法糖的情况下实例化Python列表 - How to instantiate Python list without syntactic sugar python:语法糖-是官方的吗? 文档在哪里描述? - python: syntactic sugar - is it official? where is it described in documentation? 对Python装饰器和“语法糖”感到困惑 - Confused about Python decorators and “syntactic sugar” 有无语法糖的Python装饰器之间的区别? - Difference between Python decorator with and without syntactic sugar? Python“all”函数,条件生成器表达式返回True。为什么? - Python “all” function with conditional generator expression returning True. Why? 在 python 中,属性装饰器如何在内部使用语法糖(@)工作? - How does property decorator work internally using syntactic sugar(@) in python? 接口只是“语法糖”吗? - Are Interfaces just “Syntactic Sugar”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM