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

问题描述

来自 Python Wiki

在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为什么选择逗号而不是括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:16
查看更多