【发布时间】:2019-01-28 05:18:57
【问题描述】:
我正在研究Python3 tutorial on keyword arguments,由于以下代码无法重现输出:
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
我得到的是一个排序的字典:
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
所以我尝试不调用 cheeseshop():
>>> kw = {'shopkeeper':"Michael Palin", 'client':"John Cleese", 'sketch':"Cheese Shop Sketch"}
>>> kw
{'client': 'John Cleese', 'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch'}
看起来在 3.5 版中,键是自动排序的。但在 2.7 版中,它们不是:
>>> kw
{'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch', 'client': 'John Cleese'}
我必须在2.7 中对其进行排序以同意3.5。
>>> for k in sorted(kw):
... print(k + " : " + kw[k])
...
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
因此教程中的语句:“请注意,打印关键字参数的顺序保证与函数调用中提供它们的顺序相匹配。”应该只适用于 2.7 版,而不是 3.5 版。这是真的吗?
【问题讨论】:
-
在 3.5 中,它们的顺序是随机的。如果可以的话,您应该升级到当前的 Python 3.7,这样会保留顺序。 (在 2.7 中,它们也是随机顺序的,但顺序是一致的。)
-
通常,您不应该依赖具有任何特定顺序的字典。有时,您需要 — 在这种情况下,如果您无法升级到 Python 3.7,则必须显式使用
OrderedDict而不是dict。依赖 3.4 之前的版本在某些平台上的某些实现中碰巧具有的任意但可重复的顺序是一个坏主意。
标签: python python-3.x python-2.7