Discuss / Python / 山东洛馍卷大葱

山东洛馍卷大葱

Topic source
# -*- coding: utf-8 -*-

import os
import sqlite3

db_file = os.path.join(os.path.dirname(__file__), 'test.db')
if os.path.isfile(db_file):
    os.remove(db_file)

# 初始数据:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute(
    'create table user(id varchar(20) primary key, name varchar(20), score int)')
cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
conn.commit()
cursor.close()
conn.close()


def get_score_in(low, high):
    conn = sqlite3.connect(db_file)
    cursor = conn.cursor()
    cursor.execute('select * from user where score >=? and score<=?', (low, high,))
    query_data = cursor.fetchall()
    cursor.close()
    conn.close()
    sort_list = sorted(query_data, key=lambda item: item[2])
    name_list = list(map(lambda item: item[1], sort_list))
    return name_list


# 测试:
assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)

print('Pass')

sql直接排序( ̄(∞) ̄) 

def get_score_in(low, high):
    conn = sqlite3.connect(db_file)
    cursor = conn.cursor()
    cursor.execute('select name from user where score>=? and score<=? order by score asc', (low, high))
    query_data = cursor.fetchall()
    cursor.close()
    conn.close()
    name_list = [n[0] for n in query_data]
    return name_list

  • 1

Reply