I have a list of tuples generated from some items I have in another list. I want to get the indices (first item in tuple) in a list if the second tuple items are sequential.
e.g. list called "processed"
[(1, 'Chip 1'),
(1, 'Chip 2'),
(1, 'Chip 3'),
(2, 'Chip 4'),
(4, 'Chip 1'),
(4, 'Chip 2'),
(4, 'Chip 3'),
(4, 'Chip 4'),
(5, 'Chip 5'),
(7, 'Chip 1'),
(7, 'Chip 2'),
(7, 'Chip 3'),
(7, 'Chip 4'),
(8, 'Chip 5'),
(10, 'Chip 1'),
(10, 'Chip 2'),
(10, 'Chip 3'),
(12, 'Chip 1'),
(12, 'Chip 2'),
(14, 'Chip 1'),
(16, 'Chip 1'),
(16, 'Chip 2'),
(18, 'Chip 1'),
(18, 'Chip 2'),
(20, 'Chip 1'),
(20, 'Chip 2'),
(20, 'Chip 3'),
(20, 'Chip 4'),
(23, 'Chip 1'),
(25, 'Chip 1'),
(27, 'Chip 1'),
(27, 'Chip 2')]
I can get the chips in sequential lists by using more_itertools but I don't know how to process this further. Can someone help me figure it?
import more_itertools as mit
chip_nums = [int(p[1][-1]) for p in processed]
for group in mit.consecutive_groups(chip_nums):
print(list(group))
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3]
[1, 2]
[1]
[1, 2]
[1, 2]
[1, 2, 3, 4]
[1]
[1]
[1, 2]
groups contains the indexes of elements (start and end inclusive) from the processed list which are continuous.
Note: some tuple contains the same/equal start and end value which signifies that there was no continuity.
groups = []
start = 0
for i in range(len(processed) - 1):
if int(processed[i][1].split()[-1]) + 1 == int(
processed[i + 1][1].split()[-1]
): # checks if the next element is 1 greater than previous element
pass
else:
groups.append((start, i)) # stores the start and ending index of a continuous group
start = i + 1
groups.append((start, i + 1)) # this handles the last remaining element
index_list = [[item[0] for item in processed[start : end + 1]] for start, end in groups]
Output:
[[1, 1, 1, 2], [4, 4, 4, 4, 5], [7, 7, 7, 7, 8], [10, 10, 10], [12, 12], [14], [16, 16], [18, 18], [20, 20, 20, 20], [23], [25], [27, 27]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With