Home > database >  Replace consecutive numbers in list with their min
Replace consecutive numbers in list with their min

Time:09-06

I have a list of integers and some of them are consecutive. I would like to either replace the consecutive ones with their group's minimum or delete all of them except each group's minimum. Example:

my_list = [1,2,3,4,6,7,8,9,11]

result = [1,1,1,1,6,6,6,6,11]

or even deleting them like so:

result = [1,6,11]

CodePudding user response:

For the second way,

print([x for x in my_list if x-1 not in my_list])

gives you the list of all numbers for which the previous is not in the original list

CodePudding user response:

Simple solution:

>>> from itertools import pairwise
>>> result = [lst[0]]
>>> for i, j in pairwise(lst):
...     if j - i != 1:
...         result.append(j)
...
>>> result
[1, 6, 11]

Note: itertools.pairwise was introduced in Python 3.10. If you are using an earlier version, you can consider implementing pairwise yourself or simply using indexes.

  • Related