python - python列表和元组文字中的评估顺序

标签 python

假设我们有这样的事情:

a = (fcn1(), fcn2())
b = [fcn1(), fcn2()]

Python 解释器是在 fcn2() 之前评估 fcn1(),还是未定义顺序?

最佳答案

它们是从 left to right 评估的.

来自docs (对于列表):

When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order.

使用 dis.dis() 的小测试:

In [208]: def f1():pass

In [209]: def f2():pass

In [210]: import dis

In [212]: def func():

        a = (f1(), f2())
        b  = [f1(), f2()]
       .....:     

In [213]: dis.dis(func)
  2           0 LOAD_GLOBAL              0 (f1)
              3 CALL_FUNCTION            0
              6 LOAD_GLOBAL              1 (f2)
              9 CALL_FUNCTION            0
             12 BUILD_TUPLE              2
             15 STORE_FAST               0 (a)

  3          18 LOAD_GLOBAL              0 (f1)
             21 CALL_FUNCTION            0
             24 LOAD_GLOBAL              1 (f2)
             27 CALL_FUNCTION            0
             30 BUILD_LIST               2
             33 STORE_FAST               1 (b)
             36 LOAD_CONST               0 (None)
             39 RETURN_VALUE        

注意:在赋值的情况下,首先计算右侧。

关于python - python列表和元组文字中的评估顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487350/

相关文章:

python - 启用 mypy `strict_Optional 有什么优点?

python - org-mode babel 和 matplotlib 中绘图背后的阴影

python - 持续集成、easy_install 和下载问题

python - 制作混合类型的 numpy 数组并将其写入 csv

Python if else 条件错误

python - Tensorflow feed_dict 值错误 : setting an array element with a sequence

python - 两个类之间如何通信

python - lxml:Element addnext() 和 insert() 在处理 tail 时的区别

python - 将参数列表与其自身进行比较?

python - 如何在 TensorFlow 对象检测 API 中保留类特定权重的同时重置类