0

I have a list like this,

List1 = [1,2,3,7,8,11,14,15,16]

And I want to use python to generate a new list that looks like,

List2 = ["1:3", "7:8", "11", "14:16"]

How can I do this, is for loop the option here.

I don't want to use For loop as my list has more than 30 000 numbers.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • @ForceBru Saw that question, he is completely ignoring the "11" which is present in my case. – Student of the Digital World Feb 06 '19 at 18:08
  • I don't understand your output. What are the rules here? You do consecutive with 7:8, but skip an element with 1:3 and 14:16. Then 11 you leave by itself? – I Funball Feb 06 '19 at 18:49
  • The rule is 1:3 represents 1,2,3 and 7:8 represent 7 and 8 while 11 doesn't have a 12 or 10. so, it stands as just 11. if there is a 10, then it would be 10:11, if there is a 12, then it would be 11:12, if there is both 10 and 12, then it would be 10:12. – Student of the Digital World Feb 06 '19 at 18:51
  • Why do you not want to use a for-loop? What alternative do you have to looping over your list? In any event, 30,000 is not that big for a list. Just looping over that list is taking `0.000269` seconds on my machine – juanpa.arrivillaga Feb 06 '19 at 19:37

1 Answers1

1

You can use a generator:

List1 = [1,2,3,7,8,11,14,15,16]
def groups(d):
  c, start = [d[0]], d[0]
  for i in d[1:]:
    if abs(i-start) != 1:
      yield c
      c = [i]
    else:
      c.append(i)
    start = i
  yield c

results = [str(a) if not b else f'{a}:{b[-1]}' for a, *b in groups(List1)]

Output:

['1:3', '7:8', '11', '14:16']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102