python - find lists that start with items from another list -
i have manifold of lists containing integers. store them in list (a list of lists) call biglist.
then have second list, eg [1, 2].
now want find lists out of big_list start same items small list. lists want find must have @ least items second list.
i thinking done recursively, , came working example:
def find_lists_starting_with(start, biglist, depth=0): if not biglist: # biglist empty return biglist try: new_big_list = [] # try: smallist in biglist: if smallist[depth] == start[depth]: if not len(start) > len(smallist): new_big_list.append(smallist) new_big_list = find_lists_starting_with(start, new_big_list, depth=depth+1) return new_big_list except indexerror: return biglist biglist = [[1,2,3], [2,3,4], [1,3,5], [1, 2], [1]] start = [1, 2] print(find_lists_starting_with(start, biglist))
however not satisfied code example.
do have suggestions how improve: - understandability of code - efficiency
you can try via iterator, so:
[x x in big_list if x[:len(start_list)] == start_list]
Comments
Post a Comment