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]
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.