简体   繁体   中英

spliting comma separated values and storing in separate row in python 3.x?

I have the following python list:

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

What I want as result is like this:

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

I am new to python. How can I achieve this? My code so far is like so:

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(",")

Assuming you can't resolve the issue upstream, you can use a nested list comprehension:

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

To understand how this is constructed, consider the equivalent for loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM