Python 文档将 [1, 2]
称为“list display”。
同样,它调用 {1, 2}
一个“set display ”和 {1:'a', 2:'b'}
一个“dictionary display ”。
为什么使用“显示”而不是更常见的术语“文字”?
最佳答案
来自preceding section的第一段:
For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:
- either the container contents are listed explicitly, or
- they are computed via a set of looping and filtering instructions, called a comprehension.
显示是包含“文字”和推导式的通用术语。
[1, foo(x), "bar"]
是一个列表文字(忽略必须首先评估 foo(x)
的事实)。
[foo(x) for x in A]
是一个列表理解。
两者都是列表显示。
正如 @r.ook 指出的,该语言保留术语 literal严格来说,对于生成 str
和 int
等类型的常量值的表达式。
如果您想解释为什么 f'{x}'
是文字而 [1]
不是文字,那么常量方面至关重要。前者是在运行时计算的,但结果字符串是固定的,而 [1]
可以在编译时创建一个列表,但该列表可以稍后更改。
关于python - 为什么 Python 文档将 [1, 2] 称为列表 "display"而不是 "literal"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753384/