拆分逗号分隔的值并存储在python 3.x中的单独行中?

时间:2018-07-30 09:18:48

标签: python string python-3.x list list-comprehension

我有以下python列表:

original =    [(7782, 'Mandarin, Chinese'), 
(7783, 'Italian, Conversational Spanish'), 
(7792, 'Spanish, English'), 
(7793, 'English, Italian')]

我想要的结果是这样的:

[(7782, 'Mandarin'),
(7782, 'Chinese'),
(7783, 'Italian'),
(7783, 'Coversational Spanish'),
(7792, 'Spanish'),
(7792, 'English'),
(7793, 'English'),
(7793, 'Italian') ]

我是python的新手。我该如何实现?到目前为止,我的代码如下:

import pymysql
db = pymysql.connect("localhost","root","123456","itutor" )
cursor = db.cursor()
query = "SELECT distinct user_id, language from table;"
cursor.execute(query)
r = list(cursor.fetchall())
db.close()
r2 = r[0][1].split(",")

1 个答案:

答案 0 :(得分:2)

假设您无法在上游解决问题,则可以使用嵌套列表理解:

res = [(num, lang) for num, languages in original for lang in languages.split(', ')]

[(7782, 'Mandarin'),
 (7782, 'Chinese'),
 (7783, 'Italian'),
 (7783, 'Conversational Spanish'),
 (7792, 'Spanish'),
 (7792, 'English'),
 (7793, 'English'),
 (7793, 'Italian')]

要了解其构造方式,请考虑等效的for循环:

res = []
for num, languages in original:
    for lang in languages.split(', '):
        res.append((num, lang))