简体   繁体   中英

Nested list comprehension equivalent

Is it possible to replace the following code with a list comprehension expression?

input = ['1\t2,3\t4,5', '61\t7,8\t9,0']

res = []
li = [i.split() for i in input]
for i in li:
    l = [i[0]]
    l = l + [e.split(',') for e in i[1:]]
    res.append(l)

The problem is that the first element in every sublist should be treated differently than the rest of the elements.

I have to say this isn't really that Pythonic considering readability.

>>> l = ['1\t2,3\t4,5', '61\t7,8\t9,0']
>>> [[i[0]]+[e.split(',') for e in i[1:]] for i in [x.split() for x in l]]
[['1', ['2', '3'], ['4', '5']], ['61', ['7', '8'], ['9', '0']]]
>>> input = ['1\t2,3\t4,5', '61\t7,8\t9,0']
>>> 
>>> [[a.split()[0]] + [b.split(',') for b in a.split()[1:]] for a in input]
[['1', ['2', '3'], ['4', '5']], ['61', ['7', '8'], ['9', '0']]]
>>> import csv
>>> data = ['1\t2,3\t4,5', '61\t7,8\t9,0']
>>> [x[:1] + list(csv.reader(x[1:], delimiter=','))
     for x in csv.reader(data, delimiter='\t')]
[['1', ['2', '3'], ['4', '5']], ['61', ['7', '8'], ['9', '0']]]

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