我对语句"感到困惑。在以下程序中打印(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"应该'客户'草图' '店主' 不是数字,那怎么能" 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
这让我对第一个程序中遇到的问题感到困惑。我认为它应该给我带来同样的错误。
答案 0 :(得分:0)
答案 1 :(得分:0)
以**
开头的函数参数称为“关键字参数”,它在调用函数时采用命名参数,例如:client="John Cleese"
在您的示例中。在这种情况下,“client”是名称,“John Cleese”是值。以这种方式传递的参数放在dict
中,这是一个键值存储而不是列表,您可能会在表单中熟悉它
x = {
"foo": "bar"
}
print x["foo"] # prints "bar"