【发布时间】:2017-03-27 07:14:36
【问题描述】:
我有一个这样的元组列表:
>>> all_names = c.execute("""select name from fb_friends""")
>>> for name in all_names:
... print(name)
('Jody Ann Elizabeth Lill',)
('Georgia Gee Smith',)
...(282 more)...
('Josh Firth',)
('Danny Hallas',)
我想为每个人创建一个表。首先,我需要用下划线替换所有空格,以便成为 SQLite3 表名,所以我这样做:
>>> all_names = c.execute("""select name from fb_friends""")
>>> for name in all_names:
... friends_name = name[0].replace(" ", "_")
... print(friends_name)
Jody_Ann_Elizabeth_Lill
Georgia_Gee_Smith
...(282 more)...
Josh_Firth
Danny_Hallas
所以如果我理解正确,我现在有一个列表,而不是一个元组列表..?从这个列表中创建我的所有表格应该很简单,如下所示:
>>> all_names = c.execute("""select name from fb_friends""")
>>> for name in all_names:
... friends_name = name[0].replace(" ", "_")
... c.execute("""create table {0} (`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `work` TEXT NOT NULL, `education` TEXT, `current_city` TEXT, `phone_number` TEXT, `dob` TEXT, `gender` TEXT, `sexual_orientation` TEXT, `religion` TEXT, `relationship_status` TEXT, `about_me` TEXT )""".format(friends_name))
但它所做的只是从列表中的第一个名称创建一个表,我原以为for 循环会遍历名称列表并为每个名称创建一个表,这就是我想要的,可以请大家给我一些建议:
- 使用
.replace方法是获取名称中下划线的最佳方法吗?如果不是,那是什么? - 为什么
for循环不遍历每个名称来创建表?我该如何做到这一点? - 我的方法完全正确吗?如果不是,那么什么方法会做得更好?
【问题讨论】:
-
在使用 for 循环遍历 'all_names' 变量之前是什么样子的?
-
它是一个 sqlite3.Cursor 对象,所以我需要迭代以从中获取任何东西,不是吗?
-
>>> all_names = c.execute("""select name from fb_friends""") >>> print(all_names) <sqlite3.Cursor object at 0xb7211de0> -
try: list(all_names) 我要求您在跳入循环之前显示您正在迭代的内容,因为循环似乎只迭代一次。换句话说,你确定 all_names 有很多条目要迭代吗?另一种测试方法是注释掉 c.execute() 调用,然后在 print 语句中添加名称。
-
我想为每个人创建一个表...在数据库世界中,这是非常不明智的,因为它偏离了第三范式关系模型。另外,这可能是一个失控的脚本,因为 fb_friends 可能会迅速增长以阻碍数据库。为什么要构建 280 多个相同结构的表?只需使用一个带有 name 作为字段的人员表。查询将变得更加容易,并且可以有效地扩展。
标签: python list python-3.x sqlite tuples