2013-04-25 28 views
0

所以我查詢了一個名叫golfDB數據庫,它由一個名爲Players的表5場:使用一個for循環來選擇項目,並把它們放入一個列表

  • 名稱(玩家名)
  • totalGross(從每一輪總分數的總和)
  • totalRounds(輪數扮演)
  • 帕爾斯(由標準桿的總數)
  • 小鳥(由小鳥的總數)

在下面的這個函數中,我試圖找到具有最多pars的玩家/玩家。事實證明,有兩名球員,所以我想找出一種更好的打印方式,因爲目前它打印的打印語句兩次,但最終與不同的球員打印。我希望能夠讓我所指定的球員成爲兩名球員的名單,然後以某種方式更加連貫地在打印聲明中打印球員。有任何想法嗎?

def queryDBpars(cursor): 
    """find out which player had the most pars""" 
    cursor.execute('select name, pars from players where pars = (select max(pars) from players)') 
    playerPars= cursor.fetchall() 
    for items in playerPars: 
     players= (items[0]) 
     print('The player(s) with the most pars is/are', players) 

回答

1

您可以將玩家存儲在列表中,並在打印語句中使用join來顯示組合列表。

players = list() 
for items in playerPars: 
    players.append(items[0]) 
print('The player(s) with the most pars is/are', ', '.join(players)) 

如果你想使它更優雅,你可以使用list comprehension

​​

將輸出:The player(s) with the most pars is/are player1, player2

如果你想檢查球員的數量,這樣就可以設置文本格式正確,你可以做這樣的事情。

if len(players) > 1: 
    print('The player(s) with the most pars are', ', '.join(players)) 
elif len(players) == 1: 
    print('The player with the most pars is %s' % players[0]) 
+0

列表理解會更好。 – 2013-04-25 16:11:14

+0

真@ThijsvanDien。但是,我故意要保持簡單易懂。如果我有時間,我可能會稍後更新我的答案。 – eandersson 2013-04-25 16:50:52

+0

完美有效的理由,但我仍然希望它提到。 ;)爲了檢查它是否爲空,我不建議徹底擺脫'playerPars'。循環似乎沒有必要。 – 2013-04-25 17:52:57

3

你可以使用str.join()的名字結合在一起:

playerPars = cursor.fetchall() 
print('The player(s) with the most pars is/are', 
     ', '.join(p[0] for p in playerPars)) 

這與他們之間用逗號連接的名稱。

+0

+1:顯然是更清潔的解決方案。 ;) – eandersson 2013-04-25 16:43:34

相關問題