2015-02-10 62 views
0

下面是代碼:Python中,打印帶有格式的元組,沒有工作

#! /usr/bin/python 

def goodDifference(total, partial, your_points, his_points): 

    while (total - partial >= your_points - his_points): 
     partial = partial+1 
     your_points = your_points+1 

     return (partial, your_points, his_points) 

def main(): 
    total = int(raw_input('Enter the total\n')) 
    partial = int(raw_input('Enter the partial\n')) 
    your_points = int(raw_input('Enter your points\n')) 
    his_points = int(raw_input('Enter his points\n')) 
    #print 'Partial {}, yours points to insert {}, points of the other player {}'.format(goodDifference(total, partial, your_points, his_points)) 
    #print '{} {} {}'.format(goodDifference(total, partial, your_points, his_points)) 
    print goodDifference(total, partial, your_points, his_points) 

if __name__ == "__main__": 
    main() 

兩個評論打印與格式不工作,執行它報告此錯誤時:IndexError: tuple index out of range。 最後一次打印(未評論),工作正常。 我已經閱讀了很多Python格式字符串的例子,我不明白爲什麼我的代碼不工作。

我的Python版本是2.7.6

回答

4

str.format()需要單獨的參數,而你傳遞一個元組作爲說法。因此,它將元組替換爲第一個{},然後再沒有剩下的項目留給下一個。要通過元組作爲單獨的參數,它unpack

print '{} {} {}'.format(*goodDifference(total, partial, your_points, his_points)) 
+0

*在這種情況下做什麼? – 2015-02-10 18:19:29

+0

將元組解包爲多個參數。 https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists – kindall 2015-02-10 18:20:38

+0

現在完美... *此答案很有用* – 2015-02-10 18:22:36

2

爲什麼你不只是在打印輸出元組值是多少?

t = goodDifference(total, partial, your_points, his_points) 
print '{', t[0], '} {', t[1], '} {', t[2], '}'