我混淆了语句“print(kw ) ":",keywordskw)"在下面的程序中,在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”怎么能成为语句“print(kw ) ":”keywordskw“”“中关键字的索引呢?
为了验证我的想法,我还尝试了另一个程序:
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这进一步使我对我在第一个程序中遇到的问题感到困惑,我认为它应该会向我弹出同样的错误。
发布于 2014-06-26 00:29:59
**前面的函数参数称为“关键字参数”,它在调用函数时接受命名的参数,例如:示例中的client="John Cleese"。在这种情况下,"client“是名称,”“是值。以这种方式传递的参数被放置在一个dict中,它是一个键值存储,而不是一个列表,您可能在表单中熟悉这个列表。
x = {
"foo": "bar"
}
print x["foo"] # prints "bar"https://stackoverflow.com/questions/24056599
复制相似问题