be_good_do_good be_good_do_good - 1 month ago 4x
Python Question

breaking a complex string ('2,3-5,50-60,70') into list inplace

complexstring: '2,3-5,50-52,70'

output required: [2,3,4,5,50,51,52,70]

Here is what I attempted and succeeded

a = '2,3-5,50-52,70'
data = []
[data.extend(range(int(r.split('-')[0]),int(r.split('-')[1])+1)) if r.find('-') != -1 else data.append(int(r)) for r in a.split(',')]
print data

output achieved: [2, 3, 4, 5, 50, 51, 52, 70]

But my question is there a way to do in place with in list comprehension? What I exactly mean is

data = [#perform some processing on a here to get directly output]

instead of pre-declaring list
and keep appending or extending it.

P.S: I want to achieve it with just list comprehension without defining additional function.



a = '2,3-5,50-52,70'
data = sum([[int(x)] if x.isdigit() else list(range(int(x.split('-')[0]),1+int(x.split('-')[1]))) for x in a.split(",")],[])

variant without isdigit:

data = sum([list(range(int(x.split('-')[0]),1+int(x.split('-')[1]))) if "-" in x else [int(x)] for x in a.split(",")],[])

(I use sum with a start value of [] which allows to "flatten" the created lists of one level)


[2, 3, 4, 5, 50, 51, 52, 70]

That said, that's just for fun:

  • I don't know if the performance is good, though, since there are a lot of list creations and split calls that could be avoided (actually I think it's bad)
  • It's rather easy to build, but hard to maintain/understand