在Python3中关键字是否自动排序?

2024-06-13 16:34:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究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版。这是真的吗?你知道吗


Tags: clientitshopjohnveryprintkwsketch
1条回答
网友
1楼 · 发布于 2024-06-13 16:34:22

根据@Ry和@abamert的注释,我升级到了python3.7,请参见link1link2link3,了解如何从<;3.7>;源代码构建它的步骤。需要注意的是,ubuntu16.04的Python默认版本是/usr/bin中的2.7和3.5版本。升级后,3.7驻留在/usr/local/bin中。所以我们可以有三个版本共存。你知道吗

正如他们所说的,不要依赖于某个特定版本的密钥顺序,因为版本2.7、3.5和3.7的行为是不同的:

  1. <;2.7>;顺序是随机的,但一致/可重复。你知道吗
  2. <;3.5>;顺序是随机和不一致的。你知道吗
  3. <;3.7>;输入时保留订单,因此保持一致。你知道吗
  4. 如果您想对它进行排序,请使用OrderedDict。见下文。你知道吗

例如:

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
>>>

相关问题 更多 >