gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:29:49 25 4
gpt4 key购买 nike

假设我们有这样的事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com