Python关键字输出解释 [英] Python keyword output interpretation
问题描述
我正在阅读Python 2.7教程,并且正在查看以下语句的输出:
I'm going through the Python 2.7 tutorial, and I was looking at the output of the following statement:
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
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
因此,如果我这样调用程序:
So, if I call the program as such:
cheeseshop("Cheddar", "No.", "Seriously?",
Shopkeeper="Michael Palin",
Client="John Cleese")
它输出:
Do you have any Cheddar?
I'm sorry, we're all out of Cheddar
No.
Seriously?
--------------------------------------
Client: John Cleese
Shopkeeper: Michael Palin
这是正确的.
如果将打印语句更改为print keywords
,则会得到以下表示形式:
If I change that print statement to print keywords
, I get the following representation:
{'Shopkeeper': 'Ryan Lambert', 'Client': 'John Cleese'}
我对打印keywords[kw]
只是返回名称而keywords
没有返回名称感到困惑.
I'm a bit confused on how printing keywords[kw]
just comes back with a name, and keywords
does not.
推荐答案
在Python中,您可以通过在功能参数列表的前面放置**
来传递可选的关键字参数.
In Python, you can pass optional keyword parameters by putting a **
in front of the function parameter's list.
因此,keywords
变量实际上是字典类型.因此,如果您这样做:
So the keywords
variable is actually a dictionary type. Thus, if you do:
print keywords
您回来了(重新格式化以使映射更加明显)
you get back (reformatted to make the mapping more obvious)
{
'Shopkeeper': 'Ryan Lambert',
'Client': 'John Cleese'
}
这是一本字典.如果您这样做:
which is a dictionary. And if you do:
print keywords[kw]
您将获得与键kw
关联的字典的值.因此,如果kw
是'Shopkeeper'
,则keywords[kw]
变成'Ryan Lambert'
,如果kw
是'Client'
,则keywords[kw]
变成'John Cleese'
you get back the value of the dictionary associated with the key kw
. So if kw
was 'Shopkeeper'
, then keywords[kw]
becomes 'Ryan Lambert'
, and if kw
was 'Client'
, then keywords[kw]
becomes 'John Cleese'
这篇关于Python关键字输出解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!