用于列表,字典等的Python"最佳格式化实践"

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)

  • 稍微减少git友好,因为在第一行或最后一行更改键/值会将其他语法元素引入变更集. (3认同)

dan*_*lei 28

aaronasterling的压痕风格是我喜欢的.在另一个SO问题中解释了这个以及其他几种风格.特别是Lennart Regebro的回答给出了很好的概述.

但这种风格是最受欢迎的风格:

my_dictionary = {
    1: 'something',
    2: 'some other thing',
}
Run Code Online (Sandbox Code Playgroud)

  • 我特别喜欢python允许你用逗号跟随字典,列表或元组的最后一项.这使得以后更容易重新排序或扩展序列. (5认同)
  • 一定是C/Java程序员对此投票,因为他们看到了熟悉的东西. (5认同)
  • @AndrewF我必须同意.这是JSON让我生气的唯一一件事,拒绝处理序列中的尾随逗号. (2认同)

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,我会说其他任何技术上都是错误的.


eum*_*iro 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}
Run Code Online (Sandbox Code Playgroud)

你喜欢输出吗?