九州体育网 - 十年信誉网站

关于作者

Discuss / Python / <使用SQLite>作业

<使用SQLite>作业

Topic source

Gin阿金

#1 Created at ...

#-- coding:utf-8 -- import os, 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)") cursor.close() conn.commit() conn.close()

def get_score_in(low, high): try: conn = sqlite3.connect('db_file') cursor = conn.cursor() cursor.execute('select name from user where score between ? and ? order by score',(low, high)) result = cursor.fetchall() return [x[:][0] for x in result] finally: cursor.close() conn.close()

测试:

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

ZJahon

#2 Created at ...

请问return [x[:][0] for x in result]中x[:][0]是要表白什么意思。

ZJahon

#3 Created at ...

好像理解了你的意思,不外去掉[0]也一样pass。我觉得当x在循环之中后就已经降维了,此时是以为数组,直接x[0]取出名字就好了。


  • 1

Reply

WARNING: You are using an old browser that does not support HTML5. Please choose a modern browser (Chrome / Microsoft Edge / Firefox / Sarafi) to get a good experience.