3

我正在使用 Python 2.7.3 并试图理解为什么这个脚本会乱序执行打印语句。即“-”在第二个 for 循环之后打印。

我的脚本:

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]

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', 'sketch': 'Cheese Shop Sketch', 'client': 'John Cleese'}
----------------------------------------

为什么按预期打印“-”* 40 在字典之前执行?

4

1 回答 1

8

You didn't pass in the dictionary as keywords. Use the ** syntax to do so:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           **{'shopkeeper':'Michael Palin',
           'client':"John Cleese",
           'sketch':"Cheese Shop Sketch"})

or don't use a dictionary at all:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")
于 2013-01-26T18:45:10.433 回答