vacia una rangos lista len función funcion for establecer español elementos definir crear agregar python list split integer indices

una - Python: lista dividida de enteros basada en el paso entre ellos



función range de python (4)

Tengo el siguiente problema. Tener una lista de enteros, quiero dividirla, en una lista de listas, siempre que el paso entre dos elementos de la lista de entrada original no sea 1. Por ejemplo: entrada = [0, 1, 3, 5, 6, 7 ], salida = [[0, 1], [3], [5, 6, 7]]

Escribí la siguiente función, pero es fea como el infierno, y me preguntaba si alguno de ustedes me ayudaría a encontrar una solución más agradable. Traté de usar itertools, pero no pude resolverlo.

Aquí está mi solución:

def _get_parts(list_of_indices): lv = list_of_indices tuples = zip(lv[:-1], lv[1:]) split_values = [] for i in tuples: if i[1] - i[0] != 1: split_values.append(i[1]) string = ''/''.join([str(i) for i in lv]) substrings = [] for i in split_values: part = string.split(str(i)) substrings.append(part[0]) string = string.lstrip(part[0]) substrings.append(string) result = [] for i in substrings: i = i.rstrip(''/'') result.append([int(n) for n in i.split(''/'')]) return result

¡Muchas gracias!


Aquí hay una solución que utiliza un bucle for.

def splitbystep(alist): newlist = [[alist[0]]] for i in range(1,len(alist)): if alist[i] - alist[i-1] == 1: newlist[-1].append(alist[i]) else: newlist.append([alist[i]]) return newlist


Así es como lo haría:

inp = [0, 1, 3, 5, 6, 7] base = [] for item in inp: if not base or item - base[-1][-1] != 1: # If base is empty (first item) or diff isn''t 1 base.append([item]) # Append a new list containing just one item else: base[-1].append(item) # Otherwise, add current item to the last stored list in base print base # => [[0, 1], [3], [5, 6, 7]]


Esto funciona con cualquier iterable

>>> from itertools import groupby, count >>> inp = [0, 1, 3, 5, 6, 7] >>> [list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))] [[0, 1], [3], [5, 6, 7]]


def _get_parts(i, step=1): o = [] for x in i: if o and o[-1] and x - step == o[-1][-1]: o[-1].append(x) else: o.append([x]) return o _get_parts([0, 1, 3, 5, 6, 7], step=1) # [[0, 1], [3], [5, 6, 7]])