array([ 57, 58, 59, 60, 61, 78, 79, 80, 81, 82, 83, 101, 102, 103, 104, 105, 106] These arrangements
array([57,58,59,60,61]), ([78,79,80,81,82,83]), ([101,102,103,104,105,106]) Is there a way to convert them into three arrays that have adjacent values like this?
python
>>> l = [ 57, 58, 59, 60, 61, 78, 79, 80, 81, 82, 83, 101, 102, 103, 104, 105, 106]
>>> sp = [[]]
>>> for i in range(len(l)):
if i == len(l) - 1:
sp[-1].append(l[i])
break
diff = l[i+1] - l[i]
sp[-1].append(l[i])
if diff > 1:
sp.append([])
>>> sp
[[57, 58, 59, 60, 61], [78, 79, 80, 81, 82, 83], [101, 102, 103, 104, 105, 106]]
>>>
It's not like Python, but it's possible.
If you increase the index one by one, and the difference from the next element is greater than 1, it is manipulated to be included in the new list.
# shuffled
arr = [106, 82, 80, 57, 58, 103, 59, 61, 78, 102, 79, 81, 83, 101, 104, 60, 105, 108]
def group_by_adj(list, _range=1):
arr = sorted(list)
from_idx = 0;
for curr in xrange(1, len(arr)):
if (arr[curr] - arr[curr-1] > _range):
yield arr[from_idx:curr]
from_idx = curr
yield arr[from_idx:]
#test 1
for x in group_by_adj(arr):
print(x)
#test 2, with _range options
print(list(group_by_adj(arr, 17)))
© 2024 OneMinuteCode. All rights reserved.