我正在研究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版。这是真的吗?你知道吗
根据@Ry和@abamert的注释,我升级到了python3.7,请参见link1link2和link3,了解如何从<;3.7>;源代码构建它的步骤。需要注意的是,ubuntu16.04的Python默认版本是/usr/bin中的2.7和3.5版本。升级后,3.7驻留在/usr/local/bin中。所以我们可以有三个版本共存。你知道吗
正如他们所说的,不要依赖于某个特定版本的密钥顺序,因为版本2.7、3.5和3.7的行为是不同的:
例如:
相关问题 更多 >
编程相关推荐