0

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.

Max
  • 19,654
  • 13
  • 84
  • 122

3 Answers3

2

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']]]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1
>>> 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']]]
whtsky
  • 351
  • 1
  • 4
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']]]
jamylak
  • 128,818
  • 30
  • 231
  • 230