What are the different ways to convert a generator expression to a list?(将生成器表达式转换为列表的不同方式有哪些?)

mylist = [1,2,3,4,5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)

passing a generator expression as a list is one way I learned to convert the generator expression into a list. Just curious to know if this can be other in a different way?

Solution:

Unclear if you’re looking for alternatives or just shorter.

For shorter, you don’t need an intermediate variable.

list(item for item in mylist if item > 3)

Which is the same as

[item for item in mylist if item > 3]

For alternatives of the generator, you could use filter function on mylist, but you’d still need list() function, or list-compression, or a while loop calling next() until the generator is exhausted for alternatives of making a list

————————
mylist = [1,2,3,4,5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)

将生成器表达式作为列表传递是我学会的将生成器表达式转换为列表的一种方法。只是想知道这是否可以用另一种方式?

解决方法:

不清楚你是在寻找替代品还是更短的。

简而言之,不需要中间变量。

列表(如果项目>3,则mylist中的项目对应项目)

这和

[如果项目>3,则mylist中的项目对应项目]

对于生成器的替代方案,您可以在mylist上使用filter函数,但仍然需要list()函数,或者list compression,或者调用next()的while循环,直到生成器无法生成列表为止