Wiz*_*ard 31 python code-formatting
我一直在查看Python文档,以获取大型列表和字典的代码格式化最佳实践,例如,
something = {'foo' : 'bar', 'foo2' : 'bar2', 'foo3' : 'bar3'..... 200 chars wide, etc..}
Run Code Online (Sandbox Code Playgroud)
要么
something = {'foo' : 'bar',
'foo2' : 'bar2',
'foo3' : 'bar3',
...
}
Run Code Online (Sandbox Code Playgroud)
要么
something = {
'foo' : 'bar',
'foo2' : 'bar2',
'foo3' : 'bar3',
...
}
Run Code Online (Sandbox Code Playgroud)
如何处理列表/词典的深层嵌套?
aar*_*ing 37
我的首选方式是:
something = {'foo': 'bar',
'foo2': 'bar2',
'foo3': 'bar3',
...
'fooN': 'barN'}
Run Code Online (Sandbox Code Playgroud)
dan*_*lei 28
aaronasterling的压痕风格是我喜欢的.在另一个SO问题中解释了这个以及其他几种风格.特别是Lennart Regebro的回答给出了很好的概述.
但这种风格是最受欢迎的风格:
my_dictionary = {
1: 'something',
2: 'some other thing',
}
Run Code Online (Sandbox Code Playgroud)
fro*_*wns 17
根据PEP8样式指南,有两种格式化字典的方法:
mydict = {
'key': 'value',
'key': 'value',
...
}
Run Code Online (Sandbox Code Playgroud)
要么
mydict = {
'key': 'value',
'key': 'value',
...
}
Run Code Online (Sandbox Code Playgroud)
如果你想要符合PEP8,我会说其他任何技术上都是错误的.
以您想要的任何方式定义您的字典,然后尝试:
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}
Run Code Online (Sandbox Code Playgroud)
你喜欢输出吗?