1

我对以下程序中的语句“ print(kw,":",keywords[kw])"感到困惑,在 python 中。

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)
    print(keywords)
    keys=sorted(keywords)
    print(keys)
    for kw in keys:
        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.
----------------------------------------
{'client': 'John Cleese', 'sketch': 'Cheese Shop Sketch', 'shopkeeper': 'Michael Palin'}
['client', 'shopkeeper', 'sketch']
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

在我的想法中,“kw”应该是“client”、“sketch”和“shopkeeper”,而不是数字,那么“kw”怎么可能是语句“print(kw,:”,keywords[kw)中关键字的索引])”

为了验证我的想法,我还尝试了另一个程序:

letters=['a','b']
for kw in letters:
   print(letters[kw])

并弹出一个合理的回复:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str

这进一步让我对我在第一个程序中遇到的问题感到困惑。我认为它应该向我弹出同样的错误。

4

2 回答 2

0

前面的函数参数**称为“关键字参数”,它在调用函数时采用命名参数,例如:client="John Cleese"在您的示例中。在这种情况下,“client”是名称,“John Cleese”是值。以这种方式传递的参数被放置在 a 中dict,这是一个键值存储而不是一个列表,您可能在表单中熟悉它

x = {
      "foo": "bar"
    } 
print x["foo"] # prints "bar"
于 2014-06-26T00:29:59.223 回答
0

它使用关键字实用程序,它是一种带有键名的数组。

您可以在此处的 python 文档中查看 lib 描述

事实上,**keywords 参数的特殊属性提供了执行此操作的权利。

HERE是使用它的教程(也可以理解它),这里是 stackoverflow 相关的问题。

于 2014-06-16T09:17:45.923 回答