Python括号约定

2024-10-08 23:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

您认为在代码中编写字典字面值时最常用的约定是什么?在

我会写一个可能的约定作为答案。在


Tags: 答案代码字典我会面值
3条回答

关于尾撑:我喜欢这样:

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

我将告诉您原因:因为Python代码缩进没有close标记,所以代码是这样缩进的:第一行(if、while、def等)从子句的其余部分缩进,其他行缩进的量相同。该子句的最后一行与其他行一起缩进。与第一行缩进的下一行是下一个子句的第一行,而不是这个子句的最后一行。在

因此,我喜欢使用与代码子句类似的约定来缩进数据结构,即使数据结构有一个显式的结束标记,因此可以具有更大的灵活性。在

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

我认为几乎没有标准。在

我见过两种缩进方式:

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

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

我已经看到了三个括号:

^{pr2}$

有时你会证明这些价值观:

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',
                      })

我建议你适应编写你正在编辑的代码的人的风格。如果这是你的准则:随心所欲。:-)

相关问题 更多 >

    热门问题