Python元组vs生成器 [英] Python tuple vs generator

查看:312
本文介绍了Python元组vs生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,理解为什么以下行之一返回生成器和另一个元组。

I am having a problem understanding why one of the following line returns generator and another tuple.

它在第一行中创建元组的确切原因和原因是什么?在第二行中它创建一个元组?

How exactly and why it creates the tuple in first line where in the second it creates a tuple?

sample_list = [1, 2, 3, 4]
generator = (i for i in sample_list)
tuple_ = (1, 2, 3, 4)

print type(generator)
<type 'generator'>

print type(tuple_)
<type 'tuple'>    

是因为元组是不可变对象,当我尝试在中解压缩列表时(),它不能创建元组,因为它必须更改元组元组。

Is it because tuple is immutable object and when I try to unpack list inside (), it can't create the tuple as it has to change the tuple tuple.

推荐答案

您可以将元组硬编码时创建元组,同时创建生成器以提供创建方法对象。

You can imagine tuples as being created when you hardcode the values, while generators are created where you provide a way to create the objects.

这是有效的,因为(1,2,3,4)无法成为发电机。没有什么可以生成,你只是指定了所有元素,而不是获取它们的规则。

This works since there is no way (1,2,3,4) could be a generator. There is nothing to generate there, you just specified all the elements, not a rule to obtain them.

为了使你的生成器成为一个元组,表达式(i for i)在sample_list中)必须是元组理解。没有办法让元组理解,因为理解需要一个可变数据类型。

In order for your generator to be a tuple, the expression (i for i in sample_list) would have to be a tuple comprehension. There is no way to have tuple comprehensions, since comprehensions require a mutable data type.

因此,本来应该是元组理解的语法已被重用于生成器。

Thus, the syntax for what should have been a tuple comprehension has been reused for generators.

这篇关于Python元组vs生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆