sqlite 设置al列表中元组的格式

yjghlzjz  于 2023-01-17  发布在  SQLite
关注(0)|答案(2)|浏览(150)

我使用SQLite从数据库中获取一个查询。目的是将下载次数最多的专辑排在前10位。我已经成功地做到了这一点。结果给了我一个元组列表。每个元组都由艺术家姓名、专辑标题和下载次数组成。我想用1到10之间的排序和制表符来格式化这个元组,如下所示:
我只是不知道如何改变格式。我一直回到标准的元组格式(艺术家姓名,专辑标题,下载次数)。我可以使用zip函数添加排名从1到10,但元组保持原样

import sqlite3

db = sqlite3.connect("C:\\Users\marlo\Downloads\programs\chinook.db")
cur = db.cursor()
cur.execute("""SELECT artists.name, Title, COUNT(*) as count
            FROM invoice_items
            JOIN tracks ON invoice_items.TrackId = tracks.TrackId
            JOIN albums ON tracks.AlbumId = albums.AlbumId 
            JOIN artists ON albums.ArtistId = artists.ArtistID
            GROUP BY Title
            ORDER BY count DESC
            LIMIT 10""")
Album_ranking = cur.fetchall()
print(*Album_ranking, sep = "\n")

Screenshot Code
输出:

('Chico Buarque', 'Minha Historia', 27)
('Lenny Kravitz', 'Greatest Hits', 26)
('Eric Clapton', 'Unplugged', 25)
('Titãs', 'Acústico', 22)
('Kiss', 'Greatest Kiss', 20)
('Caetano Veloso', 'Prenda Minha', 19)
('The Who', 'My Generation - The Very Best Of The Who', 19)
('Creedence Clearwater Revival', 'Chronicle, Vol. 2', 19)
('Green Day', 'International Superhits', 18)
('Creedence Clearwater Revival', 'Chronicle, Vol. 1', 18)

Screenshot Output
我是一个初学者,所以我觉得到目前为止我所做的一切都不值一提。我试图用列表理解来分离所有的元素,但这只是把所有的元素都放在了其他元素的下面,就像这样:

# formatting
Rank = [*range(1, 11, 1)]
Artist = [ranking[0] for ranking in Album_ranking]
Album = [ranking[1] for ranking in Album_ranking]
Frequency = [ranking[2] for ranking in Album_ranking]
dw1jzc5e

dw1jzc5e1#

你需要一行一行地打印,而不是一列一列地打印。另外,你可以使用enumerate来获得一个如下所示的运行索引:

for i, infos in enumerate(cur.fetchall(), start=1):
    print(i, *infos, sep="\t")

输出:

pkwftd7m

pkwftd7m2#

我不确定我的理解是否正确,但也许排序是正确的:

albums = [('Chico Buarque', 'Minha Historia', 27),
      ('Lenny Kravitz', 'Greatest Hits', 26),
      ('Eric Clapton', 'Unplugged', 25),
      ('Titãs', 'Acústico', 22),
      ('Kiss', 'Greatest Kiss', 20),
      ('Caetano Veloso', 'Prenda Minha', 19),
      ('The Who', 'My Generation - The Very Best Of The Who', 19),
      ('Creedence Clearwater Revival', 'Chronicle, Vol. 2', 19),
      ('Green Day', 'International Superhits', 18),
      ('Creedence Clearwater Revival', 'Chronicle, Vol. 1', 18)

def func(element):
     return element[2]

print(sorted(albums, key=func, reverse=True))

相关问题