我要打印我的排行榜,但是将其打印在一行而不是多行上。
到目前为止,这是我的代码:
cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()
topscore = list(topscore)
print(topscore)
当它运行时,输出如下: [('VortexHD',6),('test',0),('TestOCR',0)]
但是我希望它在这样的不同行上输出名称和分数:
VortexHD,6
测试,0
TestOCR,0
任何帮助,谢谢。
答案 0 :(得分:2)
print
自动添加一个结束行,因此只需迭代并分别打印每个值即可:
for score in topscore:
print(score)
答案 1 :(得分:1)
cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()
topscore = list(topscore)
for i in topscore:
print(i[0],i[1],sep=' , ')
print('\n')
答案 2 :(得分:0)
您可以循环输出并打印其每个元素。您不必先创建输出列表,因为fetchall()
已经返回了列表,因此您可以这样操作:
cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()
for username, score in topscore: # this uses tuple unpacking
print(username, score)
输出:
VortexHD, 6 Test, 0 TestOCR, 0
答案 3 :(得分:0)
如果您使用print(a_variable),Python具有预定义的格式,那么它将自动转到下一行。因此,要获得所需的解决方案,您需要先在元组中打印第一个元素,然后是',',然后通过索引号。
cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()
topscore = list(topscore)
for value in topscore:
print(value[0],',',value[1])