我一直在查看Python文档,了解大型列表和词典的代码格式化最佳做法,例如,
something = {'foo' : 'bar', 'foo2' : 'bar2', 'foo3' : 'bar3'..... 200 chars wide, etc..}
或
something = {'foo' : 'bar',
'foo2' : 'bar2',
'foo3' : 'bar3',
...
}
或
something = {
'foo' : 'bar',
'foo2' : 'bar2',
'foo3' : 'bar3',
...
}
如何处理列表/词典的深层嵌套?
答案 0 :(得分:37)
我的首选方式是:
something = {'foo': 'bar',
'foo2': 'bar2',
'foo3': 'bar3',
...
'fooN': 'barN'}
答案 1 :(得分:26)
aaronasterling的缩进风格是我更喜欢的。这个以及其他几种风格在another SO Question中有解释。特别是Lennart Regebro的回答给出了很好的概述。
但这种风格是最受欢迎的风格:
my_dictionary = {
1: 'something',
2: 'some other thing',
}
答案 2 :(得分:16)
根据PEP8 style guide,有两种格式化字典的方法:
mydict = {
'key': 'value',
'key': 'value',
...
}
OR
mydict = {
'key': 'value',
'key': 'value',
...
}
如果你想要符合PEP8,我会说其他任何技术上都是错误的。
答案 3 :(得分:5)
以您想要的任何方式定义您的字典,然后尝试:
from pprint import pprint
pprint(yourDict)
# for a short dictionary it returns:
{'foo': 'bar', 'foo2': 'bar2', 'foo3': 'bar3'}
# for a longer/nested:
{'a00': {'b00': 0,
'b01': 1,
'b02': 2,
'b03': 3,
'b04': 4,
'b05': 5,
'b06': 6,
'b07': 7,
'b08': 8,
'b09': 9},
'a01': 1,
'a02': 2,
'a03': 3,
'a04': 4,
'a05': 5,
'a06': 6,
'a07': 7,
'a08': 8,
'a09': 9,
'a10': 10}
你喜欢输出吗?
答案 4 :(得分:2)
如果你去ganeti(尊重PEP 8),你应该选择第三个选项。
something = {
'foo1': 'bar1',
'foo2': 'bar2',
'foo3': 'bar3',
...
}
我喜欢这个esp。因为您可以选择仅您想要的元素。我觉得通过这种方式移除或添加元素到两端都会更快。
注意:正如评论中所指出的,根据PEP,在':'(E203)之前应该没有空格。
答案 5 :(得分:1)
我更喜欢第二个或第三个。
原因:
答案 6 :(得分:1)
嗯,第一个是不行,因为你的行只有79个字符宽。关于其他两个选项,我认为这是一个品味问题,但我个人更喜欢第二种选择。
答案 7 :(得分:1)
绝对不是选项1,Python的强项之一就是它的易读性。选项1严重削弱了易读性。
在2和3中,我将回应pyfunc为两者所说的相同原因。
然而,在我自己的代码中,我更喜欢选项3,因为第一个元素有时会因为在声明行的末尾而“迷失”,并且在快速浏览代码时有时我不会立即看到它。我知道这有点傻,但思想以神秘的方式运作......
答案 8 :(得分:0)
我喜欢第二种方式:
something = {'foo' : 'bar',
'foo2' : 'bar2',
'foo3' : 'bar3',
...
'fooN': 'barN'}
答案 9 :(得分:0)
在阅读这篇文章之前,我会选择你提供的第三个选项。但现在我可能会选择那不是TörökGábor的风格:
my_dictionary = { 1:'某事', 2:'其他的东西', }
但老实说,除了你的第一个选择之外的任何事情都可能没事。
答案 10 :(得分:0)
我想提到以下选项,在PEP8中没有特别提及,但在dictionary documentation中指出:“当键是简单字符串时,有时使用关键字参数指定对更容易: “
my_dict = dict(
foo = 1,
bar = 2,
baz = 3,
...
)
但是,它不能解决缩进问题。