【问题标题】:What is the proper way to format a multi-line dict in Python?在 Python 中格式化多行 dict 的正确方法是什么?
【发布时间】:2011-09-17 07:22:42
【问题描述】:

在 Python 中,我想在我的代码中编写一个多行字典。有几种方法可以格式化它。以下是我能想到的一些:

  1. mydict = { "key1": 1,
               "key2": 2,
               "key3": 3, }
    
  2. mydict = { "key1": 1,
               "key2": 2,
               "key3": 3,
             }
    
  3. mydict = {
        "key1": 1,
        "key2": 2,
        "key3": 3,
    }
    

我知道以上任何一项在语法上都是正确的,但我假设 Python dicts 有一种首选的缩进和换行样式。这是什么?

注意:这不是语法问题。以上所有内容(据我所知)都是有效的 Python 语句,并且彼此等价。

【问题讨论】:

  • 对于 1 和 2:大括号内没有空格,请参阅 PEP 8。
  • 我想说的是,在 pythons pprint 模块中,它使用了您的第一个示例,大括号内没有空格。

标签: python indentation code-formatting multiline


【解决方案1】:

我使用#3。对于长列表、元组等也是如此。它不需要在缩进之外添加任何额外的空格。一如既往,保持一致。

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}

mylist = [
    (1, 'hello'),
    (2, 'world'),
]

nested = {
    a: [
        (1, 'a'),
        (2, 'b'),
    ],
    b: [
        (3, 'c'),
        (4, 'd'),
    ],
}

同样,这是我在不引入任何空格的情况下包含大字符串的首选方式(就像使用三引号多行字符串时一样):

data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)

【讨论】:

  • 您能否提供一些参考资料,我无法找到这方面的权威来源。 (我同意你的看法)。
  • 不要告诉他,但那个用户不知道他在说什么;P
  • 大声笑,更严重的是,我也找不到“权威”参考。如果我这样做,我会告诉你的!也许有人应该联系 Guido。
  • 这匹配 PEP 8:python.org/dev/peps/pep-0008/#indentation。在缩进部分的底部有一些列表示例。
  • 您的“嵌套”示例语法无效。
【解决方案2】:

首先,就像 Steven Rumbalski 所说,“PEP8 没有解决这个问题”,所以这是个人喜好问题。

我会使用与您的格式 3 相似但不相同的格式。这是我的,以及为什么。

my_dictionary = { # Don't think dict(...) notation has more readability
    "key1": 1, # Indent by one press of TAB (i.e. 4 spaces)
    "key2": 2, # Same indentation scale as above
    "key3": 3, # Keep this final comma, so that future addition won't show up as 2-lines change in code diff
    } # My favorite: SAME indentation AS ABOVE, to emphasize this bracket is still part of the above code block!
the_next_line_of_code() # Otherwise the previous line would look like the begin of this part of code

bad_example = {
               "foo": "bar", # Don't do this. Unnecessary indentation wastes screen space
               "hello": "world" # Don't do this. Omitting the comma is not good.
} # You see? This line visually "joins" the next line when in a glance
the_next_line_of_code()

btw_this_is_a_function_with_long_name_or_with_lots_of_parameters(
    foo='hello world',  # So I put one parameter per line
    bar=123,  # And yeah, this extra comma here is harmless too;
              # I bet not many people knew/tried this.
              # Oh did I just show you how to write
              # multiple-line inline comment here?
              # Basically, same indentation forms a natural paragraph.
    ) # Indentation here. Same idea as the long dict case.
the_next_line_of_code()

# By the way, now you see how I prefer inline comment to document the very line.
# I think this inline style is more compact.
# Otherwise you will need extra blank line to split the comment and its code from others.

some_normal_code()

# hi this function is blah blah
some_code_need_extra_explanation()

some_normal_code()

【讨论】:

  • 我喜欢行内评论。我的第一位编程教授(我之前已经在编程多年)坚持使用内联 cmets,但从未有效地解释原因。您现在已经解释了我使用了大约 20 年的一种做法。
  • 啊哈,谢谢。在编程方面,我们有相似的年龄、经验和“里程”。因此,如果您在 20 年前就已经开始进行内联评论实践(这令人印象深刻!),为什么在大约 10 年前您还在上大学的时候,您仍然需要教授的解释?只是好奇。 :-)
  • 非常好的问题 :) ATARI BASIC 和 GWbasic 实际上强制它,它们是自上而下的基于流线的编译器。这是我在纸质杂志上阅读 peter norton 的 BASIC(以及后来的 ASM 代码)时采用的东西。我在这中间学习了 Turbo Pascal,但我已经从纸质杂志的例子中学习并符合 BASIC 的限制。
  • PEP8 在某种程度上解决了这个问题,因为它建议不要在左大括号后立即添加空格,因此 OP 中的选项 1 和 2 不可用。
【解决方案3】:

由于您的键是字符串,而且我们谈论的是可读性,所以我更喜欢:

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)

【讨论】:

  • 在定义 kwargs 时不要使用空格。 c = function(a=1, b=2) 更“pythonic”。
【解决方案4】:

通常,如果您有大型 python 对象,则很难格式化它们。我个人更喜欢为此使用一些工具。

这里是python-beautifier - www.cleancss.com/python-beautify,它可以立即将您的数据转换为可自定义的样式。

【讨论】:

    【解决方案5】:
    dict(rank = int(lst[0]),
                    grade = str(lst[1]),
                    channel=str(lst[2])),
                    videos = float(lst[3].replace(",", " ")),
                    subscribers = float(lst[4].replace(",", "")),
                    views = float(lst[5].replace(",", "")))
    

    【讨论】:

    • 这不能回答问题
    【解决方案6】:

    根据我对教程的经验,第 2 项似乎总是首选,但这是个人偏好选择。

    【讨论】:

      【解决方案7】:

      通常,您不会在最后输入后包含逗号,但 Python 会为您更正。

      【讨论】:

      • 不!始终包含最后的逗号,因此如果添加新的最后一个元素,则不必更改它之前的行。这是 Python 的一大优点:实用性大于纯度。
      • 此外,此答案并未解决所提出的问题。
      • 不是每个人都喜欢尾随逗号,也许我们中少数有强迫症的人只是喜欢阅读更简洁的代码。
      猜你喜欢
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多