2013-04-25 29 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

相关问题