【问题标题】:Python Print list on separate linesPython在单独的行上打印列表
【发布时间】:2019-04-03 13:59:10
【问题描述】:

我正在尝试打印我的排行榜,但它打印在一行而不是多行。

到目前为止,这是我的代码:

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

感谢您的任何帮助。

【问题讨论】:

    标签: python list printing


    【解决方案1】:

    print 自动添加结束行,因此只需迭代并分别打印每个值:

    for score in topscore:
        print(score)
    

    【讨论】:

    • 短:'\n'.join(topscore)
    • @DroidX86 不像惯用的那样
    【解决方案2】:
    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')
    

    【讨论】:

      【解决方案3】:

      您可以循环输出并打印其每个元素。您不必先创建输出列表,因为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
      

      【讨论】:

        【解决方案4】:

        如果您使用 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])
        

        【讨论】:

        • 虽然此代码可能会解决问题,但 including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。
        猜你喜欢
        • 1970-01-01
        • 2016-12-16
        • 2018-12-22
        • 1970-01-01
        • 1970-01-01
        • 2019-09-01
        • 1970-01-01
        • 2021-08-16
        • 2023-01-03
        相关资源
        最近更新 更多