Python 字典是如何执行的?
How Python dictionaries are executed?
如果我运行下面的代码:
a={}
a[input("key: ")] = input("value: ")
口译员首先提示我 value input
然后 key input
.
这背后的原因是什么?
通常永远无法保证内部表达式的顺序。在您的情况下,解释器首先找出需要放入字典中的内容,然后找出应该放入的位置。从口译员的角度来看,这是更优化的顺序。
因为在 input('value') 调用期间可能会发生某些事情,例如异常或者您可以简单地终止您的程序。那么,在您真正拥有该值之前,为什么还要费心找出该值的位置。
如果您确实关心订单,您应该执行以下操作:
key = input('key')
a[key] = input('value')
来自docs:
Python evaluates expressions from left to right. Notice that while
evaluating an assignment, the right-hand side is evaluated before the
left-hand side.
如果我运行下面的代码:
a={}
a[input("key: ")] = input("value: ")
口译员首先提示我 value input
然后 key input
.
这背后的原因是什么?
通常永远无法保证内部表达式的顺序。在您的情况下,解释器首先找出需要放入字典中的内容,然后找出应该放入的位置。从口译员的角度来看,这是更优化的顺序。
因为在 input('value') 调用期间可能会发生某些事情,例如异常或者您可以简单地终止您的程序。那么,在您真正拥有该值之前,为什么还要费心找出该值的位置。
如果您确实关心订单,您应该执行以下操作:
key = input('key')
a[key] = input('value')
来自docs:
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.