在 Python 中,什么决定了迭代 kwargs 时的顺序?
在 python 中,我编写了这个函数来教自己 **kwargs
在 Python 中如何工作:
def fxn(a1, **kwargs):
print a1
for k in kwargs:
print k, " : ", kwargs[k]
然后我使用以下命令调用该函数
fxn(3, a2=2, a3=3, a4=4)
这是我的 Python 解释器打印的输出:
3
a3 : 3
a2 : 2
a4 : 4
Why did the for loop print the value a3 在 a2 之前,即使我先将 a2 输入到我的函数中?
In python, I wrote this function to teach myself how **kwargs
works in Python:
def fxn(a1, **kwargs):
print a1
for k in kwargs:
print k, " : ", kwargs[k]
I then called this function with
fxn(3, a2=2, a3=3, a4=4)
Here was the output that my Python interpreter printed:
3
a3 : 3
a2 : 2
a4 : 4
Why did the for loop print the value of a3 before that of a2 even though I fed a2 into my function first?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
kwargs
是一本字典。字典是无序的——简单地说,顺序是未指定的,并且是实现细节。仔细观察会发现,顺序会根据项目的哈希值、插入顺序等而发生很大变化,因此您最好不要依赖与之相关的任何内容。kwargs
is a dictionary. Dictionaries are unordered - simply put, the order is unspecified and an implementation detail. Peeking under the hood will show that the order varies wildly depending on the hash values of the items, the order of insertion, etc. so you better don't rely on anything related to it.这是一本字典。并且,正如文档中提到的,字典没有顺序(来自 http ://docs.python.org/tutorial/datastructs.html#dictionaries):
但是您可以按某种顺序处理它,例如:
使用
sorted()
:或使用
OrderedDict
类型(您可以将OrderedDict
对象作为参数传递包含所有键值对):This is a dictionary. And, as mentioned in documentation, dictionary has no order (from http://docs.python.org/tutorial/datastructures.html#dictionaries):
But you can make it processed in some order, like that:
using
sorted()
:or by using
OrderedDict
type (you can passOrderedDict
object as parameter containing all the key-value pairs):这最终在 3.6 版本中引入:
dict 现在已排序,因此保留了关键字参数顺序。
This has finally been introduced in the 3.6 release:
dict
s are now ordered, therefore the keyword argument order is preserved.不幸的讽刺是 **kwargs 的字典化意味着以下内容将不起作用(至少不是人们期望的方式):
由于关键字参数首先构建到无序字典中,因此您不能依赖它们将按照列出的顺序插入到 OrderedDict 中。 :(
The unfortunate irony is that the dict-ification of **kwargs means that the following will not work (at least not the way one would expect):
Since the keyworded args are first built into an unordered dict, you cannot depend that they will be inserted into the OrderedDict in the order they are listed. :(
由于
kwargs
是一个 Python 字典,它是作为 哈希表,它的顺序不被保留并且实际上是随机的。实际上,作为对许多编程语言中最近的安全问题的修复,将来的顺序甚至可能是程序调用之间的更改(Python 解释器的调用)。
Since
kwargs
is a Python dictionary, which is implemented as a hash table, its ordering is not preserved and is effectively random.Actually, as a fix to a recent security issue in many programming languages, in the future the order may even change between invocations of your program (invocations of the Python interpreter).
kwargs
是一个字典,在 Python 中它们没有排序,因此结果本质上是(伪)随机的。kwargs
is a dictionary, in Python these are not ordered so the result is essentially (pseudo-) random.