Python 使用for循环选择项目并将其放入列表中
因此,我正在查询一个名为golfDB的数据库,它由一个名为players的表和5个字段组成:Python 使用for循环选择项目并将其放入列表中,python,sqlite,Python,Sqlite,因此,我正在查询一个名为golfDB的数据库,它由一个名为players的表和5个字段组成: 姓名(玩家姓名) totalGross(每轮总分的总和) 总轮数(已播放的轮数) PAR(制造的PAR总数) 小鸟(制造的小鸟总数) 在下面的函数中,我试图找到PAR最多的玩家。事实证明有两个参与者,所以我试图找出一种方法使打印效果更好,因为目前它正在打印打印语句两次,但最后使用的是不同的参与者。我希望能够将我指定为参与者的内容列为两个参与者的列表,然后以某种方式在print语句中更加连贯地打印参与
- 姓名(玩家姓名)
- totalGross(每轮总分的总和)
- 总轮数(已播放的轮数)
- PAR(制造的PAR总数)
- 小鸟(制造的小鸟总数)
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)
您可以使用组合名称:
playerPars = cursor.fetchall()
print('The player(s) with the most pars is/are',
', '.join(p[0] for p in playerPars))
这将使用逗号连接名称。您可以使用以下方式组合名称:
playerPars = cursor.fetchall()
print('The player(s) with the most pars is/are',
', '.join(p[0] for p in playerPars))
这将使用逗号连接名称。您可以将玩家存储在列表中,并在print语句中使用以显示合并列表
players = list()
for items in playerPars:
players.append(items[0])
print('The player(s) with the most pars is/are', ', '.join(players))
如果你想让它更优雅,你可以使用
它将输出:PAR最多的玩家是/是玩家1,玩家2
如果您想检查播放器的数量,以便正确格式化文本,您可以执行以下操作
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])
您可以将播放机存储在列表中,并在print语句中使用以显示列表
players = list()
for items in playerPars:
players.append(items[0])
print('The player(s) with the most pars is/are', ', '.join(players))
如果你想让它更优雅,你可以使用
它将输出:PAR最多的玩家是/是玩家1,玩家2
如果您想检查播放器的数量,以便正确格式化文本,您可以执行以下操作
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])
列表理解会更好。True@ThijsvanDien。但是,我有意让它简单易懂。如果我有时间的话,我可能会在以后更新我的答案。这完全是合理的理由,但我仍然希望它被提及我不建议为了检查它是否是空的而完全删除
playerpar
。只是循环似乎没有必要。列表理解会更好。True@ThijsvanDien。但是,我有意让它简单易懂。如果我有时间的话,我可能会在以后更新我的答案。这完全是合理的理由,但我仍然希望它被提及我不建议为了检查它是否是空的而完全删除playerpar
。只是循环似乎没有必要。