Answer the question
In order to leave comments, you need to log in
Why is there a problem with sorting?
My code for displaying the top players of my bot looks like this:
@dp.message_handler(commands=['top'])
async def cmd_top(message: types.Message):
tops = cur.execute("SELECT balance FROM users").fetchall()
tops.sort()
top1 = tops[-1][0]
top2 = tops[-2][0]
top3 = tops[-3][0]
top4 = tops[-4][0]
top5 = tops[-5][0]
allt = [top1, top2, top3, top4, top5]
alltops = ""
num = 0
for x in allt:
fname = cur.execute("SELECT fname FROM users WHERE balance=?", (x,)).fetchall()
num += 1
alltops += f"{num} • {fname} - <b><i>{x}</i></b> монеток.\n"
await message.reply(f"Топ 5 богачей бота.\n\n{alltops}")
tops.sort()
TypeError: '<' not supported between instances of 'NoneType' and 'int'
Answer the question
In order to leave comments, you need to log in
The code is fabulous. Two queries instead of one, selecting all rows for the sake of sorting on the client, NULL where it shouldn't be, and so on.
All this is perfectly done at the request level to the database!
SELECT fname, balance FROM users WHERE balance IS NOT NULL ORDER BY balance DESC LIMIT 5
top5 = cur.execute('SELECT fname, balance FROM users WHERE balance IS NOT NULL ORDER BY balance DESC LIMIT 5').fetchall()
table = []
for num, (fname, x) in enumerate(top5, 1):
table.append(f'{num} • {fname} - <b><i>{x}</i></b> монеток.\n' )
await message.reply('Топ 5 богачей бота.\n\n'+''.join(table))
Apparently, the database returns empty values among the values, which causes the error. Here is her model:
tops = [(1,), (2,), (3,), (4,), (None,), (7,)]
tops.sort()
tops = [(1,), (2,), (3,), (4,), (None,), (7,)]
tops = [(0, ) if item[0] == None else item for item in tops]
allt = [item[0] for item in sorted(tops, reverse=True)][:5]
print(allt)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question