[英]querying an sqlite3 database
因此,我正在查询一个名为golfDB的数据库,该数据库包含一个名为5个字段的球员的表:
我正在使用的功能应该根据玩家的平均得分(totalGross / totalRounds)以降序列出他们。
我不完全确定该怎么做,我的代码当前是将所有组件(玩家,总得分和总回合数)分成自己的列表。 我当时在想,我可以将每个总得分列表项除以总回合列表中的每个项,但我不确定如何将这些得分链接回相应的玩家,以便对其进行排序。
我不知道是否有可能这样做,所以有人有什么建议或想法吗?
def queryDBplayers(cursor):
"""lists the players in order of their total gross score"""
cursor.execute('select name, totalGross, totalRounds from players')
answer= cursor.fetchall()
players = list()
for items in answer:
players.append(items[0])
totalGrossScore = list()
for items in answer:
totalGrossScore.append(items[1])
totalRoundsScore = list()
for items in answer:
totalRoundsScore.append(items[2])
你让这个远复杂得多,它需要的。
首先,我不明白您为什么要分开列出清单。 如果您只有一个玩家列表,则可以使用键功能非常简单地对他们进行排序:
players.sort(key=lambda p: float(p[1]) / float(p[2]))
但是,您实际上根本不应该在Python中执行此操作。 进行排序的最佳位置是在数据库中:
SELECT name, totalGross, totalRounds ORDER BY totalGross/totalRounds
与上一个问题一样,似乎您将从学习一些基本的SQL中受益。
cursor.execute('select name, totalGross, totalRounds from players')
answer= cursor.fetchall()
print sorted(answer,key=lambda x:float(x[1])/float(x[2]))
我认为这可以工作...我不知道,但您也许可以制作查询为您排序
col1,col2,col3 = zip(*big_list)
在您的情况下col1,col2,col3 = zip(*big_list)
更容易分隔像col1,col2,col3 = zip(*big_list)
类的列
players,grosses,rounds = zip(*answer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.