为什么python在元组设计中选择逗号而不是括号? [英] Why did python choose commas over parenthesis in tuple design?

查看:50
本文介绍了为什么python在元组设计中选择逗号而不是括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 python 维基

多元素元组

在 Python 中,多元素元组如下所示:

In Python, multiple-element tuples look like:

1,2,3

...

但同样,定义元组的是逗号,而不是括号.

but again, it is the commas, not the parentheses, that define the tuple.

哦,真的吗?!

那为什么:

>>> tuple((((((1, 2, 3)))))) # creates a valid tuple
# (1, 2, 3)
>>> tuple(1, 2, 3, ) # But not here
# TypeError: tuple() takes at most 1 argument (3 given)

更严重的是,我不明白为什么没有选择括号而不是逗号?

More seriously, I don't get why the parenthesis was not chosen over the commas?

因为我认为在以下情况下会产生悖论:

Because I think it would create a paradox when:

>>> 1, # is a valid tuple
# (1,)
>>> tuple([1]) # Or this
# (1,)
>>> tuple(1) # But not this one
# TypeError: 'int' object is not iterable

但是,如果您认为括号总是负责实例化 tuple,那么使用多个项目实例化 tuple 的所有问题没了.

However, if you consider that parenthesis were always in charge of instantiating a tuple, all of the problems with instantiating tuple with multiple items are gone.

例如在我想象的世界里:

e.g. in my imaginary world:

>>> (1, 2, 3) # stay valid
# (1, 2, 3)
>>> (1) # is newly valid
# (1)
>>> () # stay valid
# ()
>>> 1, 
# TypeError: int() takes exactly 1 argument (2 given) 

我知道这是一个众所周知的功能,如果重复,我已经很抱歉了.我发现了很多关于元组如何工作的类似主题,但没有一个详细解释为什么要这样创建此功能.

I know this is a well-known feature and I'm already sorry if it a duplicate. I have found lots of similar topics about how tuple worked, but none explaining in details why this feature was created like that.

我也知道这个话题可能会以基于意见的方式结束,但我最感兴趣的是技术原因(如果有的话),或者至少是历史原因.

I am also aware that this topic could be closed as opinion-based, but I am mostly interested in technical reasons (if any), or at least historical reasons.

谢谢

推荐答案

这是语法.

用逗号分隔的术语是元组、列表和集合的构建块,具体取决于它们是用方括号、花括号还是什么都不用括起来.

The terms separated by commas are a building block for tuples, lists, and sets depending on whether they are wrapped by square brackets, curly braces, or nothing at all.

指定语法时的主要挑战是平衡相同字符的多种竞争用途.逗号分隔列表、元组、字典和集合的部分.逗号还在函数调用中分隔参数.两种用途都允许使用尾随逗号(并且对于长度为 1 的元组是必需的).同样,括号有多种用途,包括函数调用和算术表达式的分组.句点用作小数点并用于 getattribute 运算符.

The chief challenge when specifying a grammar is balancing multiple competing uses of the same characters. Commas separate parts of lists, tuples, dicts, and sets. Commas also separate arguments in function calls. Trailing commas are allowed for both uses (and are required for tuples of length one). Likewise, parentheses have multiple uses including function calls and grouping for arithmetic expressions. The period serves as a decimal point and for the getattribute operator.

这篇关于为什么python在元组设计中选择逗号而不是括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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