How To Split Consecutive Elements In A List Into Sublists
I have the following list: indices_to_remove: [0,1,2,3,..,600,800,801,802,....,1200,1600,1601,1602,...,1800] I have basically 3 subsets of consecutive indices: 0-600 800-1200 16
Solution 1:
I like to use generators for this sort of problem. You can do this like:
Split Non-Consecutive Data:
def split_non_consequtive(data):
data = iter(data)
val = next(data)
chunk = []
try:
while True:
chunk.append(val)
val = next(data)
ifval != chunk[-1] + 1:
yield chunk
chunk = []
except StopIteration:
if chunk:
yield chunk
Test Code:
indices_to_remove = (
list(range(0, 11)) +
list(range(80, 91)) +
list(range(160, 171))
)
for i in split_non_consequtive(indices_to_remove):
print(i)
Results:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
[160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170]
Solution 2:
Another way is using more_itertools.consecutive_groups
:
(used @Stephen's list for an example):
import more_itertools as mit
forgroupin mit.consecutive_groups(indices_to_remove):
print(list(group))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
[160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170]
Solution 3:
Without making it complicated, you can simply solve it something like this :
defchunk_lists_(data_):
consecutive_list = []
for chunks inrange(len(data_)):
try:
#check consecutivenessif data_[chunks + 1] - data_[chunks] == 1:
#check if it's already in listif data_[chunks] notin consecutive_list:
consecutive_list.append(data_[chunks])
#add last one too
consecutive_list.append(data_[chunks + 1])
else:
#yield here and empty listyield consecutive_list
consecutive_list = []
except Exception:
passyield consecutive_list
Test:
#Stephen's list print(list(chunk_lists_(list(range(0, 11)) +
list(range(80, 91)) +
list(range(160, 171)))))
output:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90], [160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170]]
Post a Comment for "How To Split Consecutive Elements In A List Into Sublists"