python-3.x - Python - SQLite - 根据元组信息插入值
问题描述
我有一个 sqlite 表:
conn.execute("""CREATE TABLE IF NOT EXISTS students(
ID integer not null primary key,
Department text ,
Standing text ,
GPA real,
unique(ID)
);""")
我有一个元组列表:
all_info =[('MATH', 70, 10, 20), ('BIOLOGY', 82, 12, 15), ('CHEMISTRY', 78, 30, 20), ('COMPUTER SCIENCE', 113, 5, 15), ('INFORMATICS', 138, 16, 2), ('ENGLISH', 94, 17, 33), ('SPANISH', 118, 7, 42), ('BIOCHEMISTRY', 104, 14, 39),
元组包含每个部门的学生人数信息。比如数学系有70名优等生,10名见习生和20名普通学生,总共有100名学生。
我需要根据元组中的信息将数据插入到学生数据库中。学生表的期望结果:
ID Department Standing GPA
1 Math Honors 93
2 Math Honors 93
3 Math Probation 60
...and so on.
(there would be 70 entries of math students in Honors standing with a GPA of 93.)
如果学生是荣誉学生,他们的 GPA 将是 93,如果学生处于试用期,他们的 GPA 将是 60,如果学生处于正常状态,他们的 GPA 将是 80。
我无法根据元组列表中的信息以编程方式将值插入到学生表中。
谢谢你。
编辑1:我被困在从哪里开始,我想循环遍历元组列表
for item in all_info:
ID = randint(1,99999)
num_honor = item[1]
num_prob = item[2]
num_norm = item[3]
cur.execute(INSERT statement..)
但这只会输入每个元组中的内容,根据元组中的数字插入行的任何想法?
解决方案
这就是你要找的
for each_tuple in all_info:
Department = each_tuple[0]
students_list = [(Department, 'Honors', 93) for i in range (0, each_tuple[1])] + [(Department, 'Probation', 60) for i in range (0, each_tuple[3])]+ [(Department, 'Normal', 80) for i in range (0, each_tuple[2])]
cur.executemany('INSERT INTO students VALUES(?,?,?);',student_list)
推荐阅读
- javascript - 如何取消 setIntervall 功能?
- php - PHP 从 5.4 升级到 5.6 - 简单功能的奇怪错误
- android - 如何减少 logcat 延迟?
- java - 我可以在将 Object 与另一个数组进行比较时更改它的一个值吗?
- java - 如何在 RecyclerView Android 中自定义 ItemTouchHelper
- r - 来自 googleAuthR 包的反应式表达式中的 curl 错误:收到了意外的 TLS 数据包
- javascript - 如何使用 js 或 jquery 以编程方式按下任何键盘键?
- php - 我想为显示的每个项目创建一个增量编号
- regex - 正则表达式匹配字符串#substring
- rocket-chip - 你能合成RSICV火箭芯片测试工具模块吗?