Python 括号规范

5 投票
5 回答
4577 浏览
提问于 2025-04-15 14:21

你觉得在代码中写字典时,通常使用什么样的约定呢?

我会把一种可能的约定写在下面作为回答。

5 个回答

8

关于结束大括号的问题:我更喜欢这样写:

my_dictionary = {
   'a': 'first value',
   'b': 'second',
   }

我来告诉你原因:因为在Python中,代码是通过缩进来表示结构的,没有像其他语言那样的结束标记。比如说,第一行(如果是if、while、def等)会比后面的行少缩进,后面的行都缩进相同的量。而这个结构的最后一行和其他行是一样缩进的。接下来,如果有一行和第一行缩进相同的,那它就是下一个结构的第一行,而不是当前结构的最后一行。

所以我喜欢用类似的缩进方式来表示数据结构,尽管数据结构有明确的结束标记,这样其实可以更灵活一些。

15

我觉得几乎没有什么标准。

我见过两种缩进方式:

Indent 1:
my_dictionary = {
    'uno': 'something',
    'number two': 'some other thing',
}

Indent 2:
my_dictionary = {'uno': 'something',
                 'number two': 'some other thing',
                 }

我见过三种放置结束括号的位置:

End 1:
my_dictionary = {'uno': 'something',
                 'number two': 'some other thing',
}

End 2:
my_dictionary = {'uno': 'something',
                 'number two': 'some other thing',
                 }

End 3:
my_dictionary = {'uno': 'something',
                 'number two': 'some other thing',}

有时候你还会对值进行对齐:

my_dictionary = {'uno':        'something',
                 'number two': 'some other thing',
                 }

有时候甚至对冒号也进行对齐:

my_dictionary = {'uno'        : 'something',
                 'number two' : 'some other thing',
                 }

这看起来有点奇怪。

有时候你会在最后加个逗号,有时候则不加:

my_dictionary = {'uno': 'something',
                 'number two': 'some other thing'}

有时候如果能放下,所有内容会放在一行上:

my_dictionary = {'uno': 'something', 2: 'some other thing'}

每个人似乎都有自己的一套风格。我个人倾向于你在例子中使用的风格,除非有特别的原因不这样做。常见的原因是当你在某个语句中使用字典时。比如:

amethodthattakesadict({'hey': 'this',
                       'looks': 'a',
                       'bit': 'shitty',
                      })

我建议你适应一下你正在编辑的代码作者的风格。如果是你自己的代码:随便你怎么写。:-)

21
my_dictionary = {
    1: 'something',
    2: 'some other thing',
}

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答