Pythonic way to convert a list of integers into a string of comma-separated ranges

后端 未结 7 766
感情败类
感情败类 2020-12-01 05:06

I have a list of integers which I need to parse into a string of ranges.

For example:

 [0, 1, 2, 3] -> \"0-3\"
 [0, 1, 2, 4, 8] -> \"0-2,4,8\"
         


        
相关标签:
7条回答
  • 2020-12-01 05:33

    Whether this is pythonic is up for debate. But it is very compact. The real meat is in the Rangify() function. There's still room for improvement if you want efficiency or Pythonism.

    def CreateRangeString(zones):
        #assuming sorted and distinct
        deltas = [a-b for a, b in zip(zones[1:], zones[:-1])]
        deltas.append(-1)
        def Rangify((b, p), (z, d)):
            if p is not None:
                if d == 1: return (b, p)
                b.append('%d-%d'%(p,z))
                return (b, None)
            else:
                if d == 1: return (b, z)
                b.append(str(z))
                return (b, None)
        return ','.join(reduce(Rangify, zip(zones, deltas), ([], None))[0])
    

    To describe the parameters:

    • deltas is the distance to the next value (inspired from an answer here on SO)
    • Rangify() does the reduction on these parameters
      • b - base or accumulator
      • p - previous start range
      • z - zone number
      • d - delta
    0 讨论(0)
提交回复
热议问题