简体   繁体   中英

Converting a list having 1 comma-seperated string into 2d-list

I don't know much about python's map / reduce function but is there a way to convert this input list to 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']
    ]

As of now i am only doing this by using loops and it does not look like an efficient method to do so:

inp[3]=inp[3].split(',')
out=[]
for i in inp[3]:
    k=list(inp)
    k[3]=i
    out.append(k)   

Given the hard constraints, you can speed it up a bit make it a bit more tidy using list comprehension and slicing:

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 won't reduce the complexity. In fact, it will probably run slower than your approach for your example as it has to perform 3 list creations and a list concatenation per each entry in inp[3] and unless inp[3] is very long, list comprehension won't show its real advantage to offset the list creation overhead.

You can find the index of your intended string with a generator expression within next function and then simply create your expected result with a list comprehension:

In [19]: ind = next(i for i, j in enumerate(inp) if isinstance(j, str) and ',' in j)

In [20]: [[*inp[:ind], i, *inp[ind + 1:]] for i in inp[ind].split(',')]
Out[20]: 
[[1, 2, 3, 'a', 4, 'blah'],
 [1, 2, 3, 'b', 4, 'blah'],
 [1, 2, 3, 'c', 4, 'blah']]

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