是否可以用列表推导表达式替换以下代码?
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)
问题是每个子列表中的第一个元素应该与其他元素区别对待。
答案 0 :(得分:2)
我不得不说,考虑到可读性,这并不是Pythonic。
>>> 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']]]
答案 1 :(得分: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']]]
答案 2 :(得分: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']]]