我正在研究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版。这是真的吗?
发布于 2018-08-27 13:01:10
在@Ry和@abamert的评论之后,我升级到了Python3.7,有关如何从<3.7>源代码构建它的步骤,请参阅link1 link2和link3。需要注意的是,Ubuntu 16.04的Python默认版本是/usr/bin中的2.7和3.5版本。升级后,3.7驻留在/usr/local/bin中。所以我们可以有三个版本共存。
正如他们所说的,不要依赖特定版本的键顺序,因为2.7、3.5和3.7版本的行为是不同的:
consistent/repeatable.
例如:
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> kw = {'shopkeeper':"Michael Palin", 'client':"John Cleese", 'sketch':"Cheese Shop Sketch"}
>>> kw
{'client': 'John Cleese', 'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch'}
>>>
>>> from collections import OrderedDict
>>> kws = OrderedDict(sorted(kw.items(), key = lambda x:x[0]))
>>> kws
OrderedDict([('client', 'John Cleese'), ('shopkeeper', 'Michael Palin'), ('sketch', 'Cheese Shop Sketch')])
>>> for i in kws:
... print(i + " :\t" + kws[i])
...
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
>>>https://stackoverflow.com/questions/51958496
复制相似问题