Converts a list with 1 comma-separated string to a two-dimensional list… here is a solution to the problem.
Converts a list with 1 comma-separated string to a two-dimensional list
I don’t know much about python’s map
/reduce
function, but is there a way to convert this input list to a given output?
inp = [1,2,3,"a,b,c",4,"blah"]
outp = [
[1,2,3,'a',4,'blah'],
[1,2,3,'b',4,'blah'],
[1,2,3,'c',4,'blah']
]
So far, I’ve only done this by using loops, and it doesn’t look like an effective approach :
inp[3]=inp[3].split(',')
out=[]
for i in inp[3]:
k=list(inp)
k[3]=i
out.append(k)
Solution
Given the hard constraints, you can speed up using list understanding and slicing to make it cleaner a bit:
inp = [1, 2, 3, "a,b,c", 4, "blah"]
outp = [inp[:3] + [i] + inp[4:] for i in inp[3].split(",")]
# [[1, 2, 3, 'a', 4, 'blah'],
# [1, 2, 3, 'b', 4, 'blah'],
# [1, 2, 3, 'c', 4, 'blah']]
But it doesn’t reduce complexity. In fact, for your example, it may run slower than your method because it must perform 3 list creations and a list join for each entry in inp[3
], unless inp[3]
is long and list understanding does not show its real advantage of offsetting list creation overhead.