如何使用Python将逗号分隔的值拆分为多行

时间:2016-09-26 08:28:43

标签: python sqlite

我正在使用Python和SQLite来操作数据库。

我有一个SQLite表Movies,如下所示:

| ID             | Country     
+----------------+-------------
| 1              | USA, Germany, Mexico 
| 2              | Brazil, Canada
| 3              | Peru

我想在Country中拆分逗号分隔值并将其插入另一个表 Countries,以便Countries表看起来像这样

| ID             | Country     
+----------------+-------------
| 1              | USA
| 1              | Germany
| 1              | Mexico
| 2              | Brazil
| 2              | Canada
| 3              | Peru

如何拆分Country表格中Movies列的值并将其插入Country表格中的Countries列?

根据this post,我无法使用纯SQLite完成此任务。我将如何使用Python进行操作?

2 个答案:

答案 0 :(得分:0)

使用Python,

cursor.execute("""Select * from Movies""")
all_data = cursor.fetchall()
cursor.execute("""CREATE TABLE IF NOT EXISTS Countries
                    (ID TEXT,
                    Country TEXT)""")
for single_data in all_data:
    countries = single_data[1].split()
    for single_country in countries:
        cursor.execute("""INSERT INTO Countries VALUES(%s,"%s")"""%(single_data[0],single_country))
    conn.commit()

答案 1 :(得分:0)

您可以使用通用表表达式在纯SQLite中解决此问题。

create table movies(id integer primary key, country text);
insert into movies values
(1,'USA, Germany, Mexico'), (2,'Brazil, Canada'), (3,'Peru');

create table countries(id integer, country text);
insert into countries
WITH split(id, country, str) AS (
    SELECT id, '', country||',' FROM movies
    UNION ALL SELECT id,
    trim(substr(str, 0, instr(str, ','))),
    substr(str, instr(str, ',')+1)
    FROM split WHERE str!=''
) SELECT id, country FROM split WHERE country!='' ORDER BY id;

SELECT * FROM countries;

id|country
1|USA
1|Germany
1|Mexico
2|Brazil
2|Canada
3|Peru