1

So I am having trouble thinking of a way to get different ranges from one list. The code is as follows:

data = [101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 115, 116, 117, 118, 119, 121]
f_range = []

The output from the print() needs to look something like:

101-106, 108-112, 115-119, 121

I would need to group these be sequential increasing order.

Obstupesco
  • 55
  • 6
  • 2
    Is it meant to be `108-112`? – Paolo Jun 28 '18 at 21:23
  • yes sorry, i'll fix that – Obstupesco Jun 28 '18 at 21:24
  • You should probably explicitly state what you're trying to do, instead of letting us figure it out from the input-output relationship. It seems you want to group together sequentially increasing values together, so that a gap in the sequence would create a new group. – Reti43 Jun 28 '18 at 21:28
  • @Patrick: Looks close enough to me to be a dup—I'd vote to close it myself, but I can't change the "Too broad" vote I already entered. – martineau Jun 28 '18 at 21:30

1 Answers1

1

Try this:

min = sorted(data)[0]
max = 0
step = 1  # Increment between each consecutive number
for c, item in enumerate(sorted(data)):
    try:
        if item + step != sorted(data)[c + 1]:
            max = item
            print (str(min) + "-" + str(max))
            min = sorted(data)[c + 1]
    except IndexError:
        max = item
        print (str(min) + "-" + str(max))
        break

Hope this helps.

Hypnotron
  • 96
  • 8