所以我正在查询名为golfDB的数据库,它包含一个名为player的表,包含5个字段:
在下面这个函数中,我试图找到最多的播放器/播放器。事实证明,有两个玩家,所以我试图找到一种方法使这个打印更好,因为目前它打印两次打印声明,但最后不同的播放器。我希望能够让我所指定的玩家成为两个玩家的列表,然后以更加一致的方式在打印语句中打印玩家。有什么想法吗?
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)
答案 0 :(得分:3)
您可以使用str.join()
来组合名称:
playerPars = cursor.fetchall()
print('The player(s) with the most pars is/are',
', '.join(p[0] for p in playerPars))
这会将名称与逗号加在一起。
答案 1 :(得分:1)
您可以将播放器存储在列表中,并使用print语句中的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。
players = [player[0] for player in playerPars]
输出: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])