简体   繁体   English

Python打印列表在单独的行上

[英]Python Print list on separate lines

I'm trying to print my leader board out however its printing it on one line instead of multiple. 我正在尝试打印我的排行榜,但是它在一行而不是多行打印。

So far this is my code: 到目前为止这是我的代码:

cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()

topscore = list(topscore)

print(topscore)

And when it runs it outputs like this: [('VortexHD', 6), ('test', 0), ('TestOCR', 0)] 当它运行时,输出如下:[('VortexHD',6),('test',0),('TestOCR',0)]

However i want it to output the names and score on separate lines like this: 但是我希望它在单独的行上输出名称和分数,如下所示:

VortexHD, 6 VortexHD,6

Test, 0 测试,0

TestOCR, 0 TestOCR,0

any help is appreciated thank you. 任何帮助表示赞赏谢谢。

print automatically adds an endline, so just iterate and print each value seperately: print自动添加一个endline,所以只需迭代并单独打印每个值:

for score in topscore:
    print(score)
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')

You can just loop over the output and print its every element. 您可以循环输出并打印其每个元素。 You don't have to create a list of the output first, since fetchall() returns a list already, so you can do it like this: 您不必首先创建输出列表,因为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)

Output: 输出:

 VortexHD, 6 Test, 0 TestOCR, 0 

Python has a predefined format if you use print(a_variable) then it will go to next line automatically.So, to get the required solution you need to print first element in tuple followed ',' and then second element by accessing with index number. Python有一个预定义的格式,如果你使用print(a_variable)然后它会自动转到下一行。所以,要获得所需的解决方案,你需要在元组中打印第一个元素,然后按','然后通过索引号访问第二个元素。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM