Friends, imagine a list of pairs of elements (x, y):
lista = [(13, 38), (14, 35), (14, 36), (15, 33), (15, 34), (15, 35), (15, 36), (18, 31), (18, 32), (19, 33), (22, 34), (22, 29), (23, 30), (23, 31), (24, 32)]
Would I have to create sublists with the pairs of elements in which the first element (x) is in sequence? For example, in this case it would be:
lista = [[(13, 38), (14, 35), (14, 36), (15, 33), (15, 34), (15, 35), (15, 36)], [(18, 31), (18, 32), (19, 33)], [(22, 34), (22, 29), (23, 30), (23, 31), (24, 32)]]
Grupo #0: [(13, 38), (14, 35), (14, 36), (15, 33), (15, 34), (15, 35), (15, 36)] Grupo #1: [(18, 31), (18, 32), (19, 33)] Grupo #2: [(22, 34), (22, 29), (23, 30), (23, 31), (24, 32)]
Since the number of sublists can vary, depending on the number of elements in the list.
A member here in the forum passed the code below , I initially in another post I did not express myself correctly and I went through a simple list, it worked very well, the question is that I will work with pairs of elements, who can help thanks :
# Sua lista original
lista = [1, 2, 2, 3, 3, 3, 6, 6, 7, 11, 12, 12, 13, 14, 14]
# Importa a biblioteca NumPy
import numpy as np
# Separa em grupos usando como índices da separação os locais onde ocorre uma
# diferença entre o item atual e o próximo maior do que 1
grupos = np.split(lista, [i+1 for i,j in enumerate(np.diff(lista)) if j > 1])
# Imprime os grupos produzidos
for i, g in enumerate(grupos):
print('Grupo #{}: {}'.format(i, g.tolist()))
It produces the following output:
Grupo #0: [1, 2, 2, 3, 3, 3]
Grupo #1: [6, 6, 7]
Grupo #2: [11, 12, 12, 13, 14, 14]