Formatting consecutive numbers

后端 未结 5 2047
轻奢々
轻奢々 2021-01-18 15:00

I\'m trying to format a list of integers with Python and I\'m having a few difficulties achieving what I\'d like.

Input is a sorted list of Integers:



        
5条回答
  •  孤独总比滥情好
    2021-01-18 15:48

    Not the most readable solution but gets the job done. One can first determine jumps in your data (jump = difference between two elements is greater than 1). Then you just loop through you original list and collect the respective elements and join them to a string.

    import numpy as np
    
    l = np.array([1, 2, 3, 6, 8, 9])
    
    # find indexes of jumps in your data
    l_diff = np.where(np.diff(l) > 1)[0] + 1
    
    # add one index which makes slicing easier later on
    if l_diff[0] != 0:
        l_diff = np.insert(l_diff, 0, 0)
    
    # add all the data which are groups of consecutive values
    res = []    
    for ix, i in enumerate(l_diff):
        try:
            sl = l[i:l_diff[ix + 1]]
            if len(sl) > 1:
                res.append([sl[0], sl[-1]])
            else:
                res.append(sl)
        # means we reached end of l_diff
        except IndexError:
            sl = l[i:]
            if len(sl) > 1:
                res.append([sl[0], sl[-1]])
            else:
                res.append(sl)
    
    
    # join the data accordingly, we first have to convert integers to strings
    res = ', '.join(['-'.join(map(str, ai)) for ai in res])
    

    Then res is

    '1-3, 6, 8-9'
    

提交回复
热议问题