Python在单独的行上打印列表
我试图打印出我的领导委员会,但它打印在一行,而不是多个 到目前为止,这是我的代码:Python在单独的行上打印列表,python,list,printing,Python,List,Printing,我试图打印出我的领导委员会,但它打印在一行,而不是多个 到目前为止,这是我的代码: 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)
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)]
但是,我希望它在单独的行上输出名称和分数,如下所示:
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)
涡流HD,6
测试,0
TestOCR,0
感谢您的帮助。
print
会自动添加一个结束行,因此只需重复并分别打印每个值:
对于topscore中的分数:
打印(分数)
您可以在输出上循环并打印其每个元素。您不必首先创建输出列表,因为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
Python有一个预定义的格式,如果您使用print(一个_变量),那么它将自动转到下一行。因此,要获得所需的解决方案,您需要打印元组中的第一个元素,后跟“,”,然后通过使用索引号访问第二个元素
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])
简短:
'\n'.join(topscore)
@DroidX86没有那么惯用。虽然这段代码可以解决这个问题,但它如何以及为什么解决这个问题将真正有助于提高您的文章质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加解释,并说明适用的限制和假设。