为什么Python中没有元组理解?

本文翻译自:Why is there no tuple comprehension in Python?

As we all know, there's list comprehension, like 众所周知,列表理解

[i for i in [1, 2, 3, 4]]

and there is dictionary comprehension, like 并且有字典理解,例如

{i:j for i, j in {1: 'a', 2: 'b'}.items()}

but

(i for i in (1, 2, 3))

will end up in a generator, not a tuple comprehension. 将最终生成器,而不是tuple理解。 Why is that? 这是为什么?

My guess is that a tuple is immutable, but this does not seem to be the answer. 我的猜测是tuple是不可变的,但这似乎不是答案。


#1楼

参考:https://stackoom.com/question/194Wx/为什么Python中没有元组理解


#2楼

我最好的猜测是,他们用完了括号,并认为这对警告添加“丑陋”语法没有足够的帮助...


#3楼

You can use a generator expression: 您可以使用生成器表达式:

tuple(i for i in (1, 2, 3))

but parentheses were already taken for … generator expressions. 但是对于...生成器表达式,已经使用了括号。


#4楼

I believe it's simply for the sake of clarity, we do not want to clutter the language with too many different symbols. 我相信这只是为了清楚起见,我们不想用太多不同的符号来使语言混乱。 Also a tuple comprehension is never necessary , a list can just be used instead with negligible speed differences, unlike a dict comprehension as opposed to a list comprehension. 同样, 不需要 tuple理解,也可以使用速度差可以忽略的列表来代替,而不是字典理解而不是列表理解。


#5楼

Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments. 理解通过循环或迭代项并将它们分配到容器中来工作,元组无法接收分配。

Once a Tuple is created, it can not be appended to, extended, or assigned to. 创建元组后,将无法对其进行追加,扩展或分配。 The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container). 修改元组的唯一方法是是否可以将其对象之一本身分配给它(是非元组容器)。 Because the Tuple is only holding a reference to that kind of object. 因为元组仅持有对此类对象的引用。

Also - a tuple has its own constructor tuple() which you can give any iterator. 另外-元组有自己的构造函数tuple() ,您可以给它提供任何迭代器。 Which means that to create a tuple, you could do: 这意味着要创建一个元组,您可以执行以下操作:

tuple(i for i in (1,2,3))

#6楼

Raymond Hettinger (one of the Python core developers) had this to say about tuples in a recent tweet : Raymond Hettinger(Python核心开发人员之一)在最近的一条推文中曾这样说过元组:

#python tip: Generally, lists are for looping; #python提示:通常,列表用于循环; tuples for structs. 结构的元组。 Lists are homogeneous; 列表是同质的; tuples heterogeneous. 元组异构。 Lists for variable length. 列出可变长度。

This (to me) supports the idea that if the items in a sequence are related enough to be generated by a, well, generator, then it should be a list. (对我来说)支持这样的想法:如果序列中的项目相关性足以由生成器生成,那么它应该是一个列表。 Although a tuple is iterable and seems like simply a immutable list, it's really the Python equivalent of a C struct: 尽管元组是可迭代的,并且看起来只是一个不可变的列表,但它实际上与C结构的Python等效:

struct {
    int a;
    char b;
    float c;
} foo;

struct foo x = { 3, 'g', 5.9 };

becomes in Python 成为Python

x = (3, 'g', 5.9)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值