在创建list/tuple时多写一个逗号


缘由:

在看一些Python代码的时候会发现有人在创建list/tuple的时候会在最后一个元素后面添加一个’逗号’,而且也不报错,对有一点强迫症的我来说这不可忍受,需要删掉。不过后来想想既然别人这么写应该还是有一定道理的,于是,就有了下文。

搜索关键字:
  • python create a list with one more comma
  • python create a tuple with one more comma
参考链接:
参考解答:

首先,在Python中创建一个list/tuple时,在最后一个元素后面添加一个’逗号’是没问题的;

其次,这样做的好处在于:在编辑“多行元素的list”时更不容易犯错(忘记添加/删除’逗号’);以及在diff代码时更好的观感。

=

The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.

=

It’s a common syntactical convention to allow trailing commas in an array, languages like C and Java allow it, and Python seems to have adopted this convention for its list data structure. It’s particularly useful when generating code for populating a list: just generate a sequence of elements and commas, no need to consider the last one as an special case that doesn’t have a comma at the end.

==

Python newbies often have some confusion about how to make one-element tuples. VenkataSubramanian provided a nice summary of Python’s tuple syntax [1].

Zero Element Tuples

In Python, zero-element tuples look like:

()

In this form, unlike the other tuple forms, parentheses are the essential elements, not commas.

One Element Tuples

One-element tuples look like:

1,

The essential element here is the trailing comma. As for any expression, parentheses are optional, so you may also write one-element tuples like

(1,)

but it is the comma, not the parentheses, that define the tuple.

Multiple Element Tuples

In Python, multiple-element tuples look like:

1,2,3

The essential elements are the commas between each element of the tuple. Multiple-element tuples may be written with a trailing comma, e.g.

1,2,3,

but the trailing comma is completely optional. Just like all other expressions in Python, multiple-element tuples may be enclosed in parentheses, e.g.

(1,2,3)

or

(1,2,3,)

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

=EOF=

,

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注