python - 为什么 Python 文档将 [1, 2] 称为列表 "display"而不是 "literal"?

标签 python list dictionary set literals

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严格来说,对于生成 strint 等类型的常量值的表达式。

如果您想解释为什么 f'{x}' 是文字而 [1] 不是文字,那么常量方面至关重要。前者是在运行时计算的,但结果字符串是固定的,而 [1] 可以在编译时创建一个列表,但该列表可以稍后更改。

关于python - 为什么 Python 文档将 [1, 2] 称为列表 "display"而不是 "literal"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753384/

相关文章:

python - 制作字典时尝试保留重复项

python - Pandas:按 ID 分组并删除包含最多 NaN 值的行

Python:将列表中的元素相互比较

java - 从列表中删除元素,哪种代码风格更好?

python - 扩展 python 字典来表达共享列表值

python - 在不知道键的情况下访问 python dict() 的值

python - 对象、列表和我老化的大脑

python - 使用 numpy.einsum 转置时间矩阵 : x^T * x

python - 将二维动态指针数组作为参数传递给 cython 中的函数

python - 了解嵌套列表理解的评估顺序