-1

I'm attempting to find a way for a given list to convert into multiple sub lists.

This works, however, the next thing I want is for the lists to only output when they are adjacent to one another. for example right now ['a','b','c'] outputs:

[],['a'],['b'],['c'],['a', 'b'],['a','c'] etc, I don't want ['a','c'] as they should not go next to each other. Can anyone point me in the right direction?

def list_thing(theList):
    initial = []
    lists = [initial]
    for i in range(len(theList)):
        original = lists[:]
        new = theList[i]
        for j in range(len(output)):
            lists[j] = lists[j] + [new]
        lists = lists + output
    return lists

edit: To clarify, as I have been asked, I would also like ['a','b','c'] as they are a possible result.

Just to explain further ['a','b','c','d'] would give combos like ['a','b'], ['b','c'],['c','d'], ['a','b','c','d'] These would be acceptable answers.

While ['a','b','c'] ['a','c'] would not as they are not individually next to each other or part of the larger string.

Shikari
  • 25
  • 5
  • 1
    What about `['a','b','c']` itself? If not, because you do not want the list itself, or because you want only lists with at most two elements? – tobias_k Jan 06 '21 at 15:58
  • What do you mean by they should not go next to each other? Is it because a and c are not continuous in the alphabet? – Niteya Shah Jan 06 '21 at 15:58
  • Sounds like that you just want to take a slice the list. Now try to compute all the possible start/end indices. – user202729 Jan 06 '21 at 16:01

1 Answers1

0

I think this achieves what you're after:

>>> def lister(some_list):
...   result = [[]]
...   result.extend([i] for i in some_list)
...   result.extend(map(list, zip(some_list, some_list[1:])))
...   result.append(some_list)
...   return result
... 
>>> lister(['a', 'b', 'c', 'd'])
[[], ['a'], ['b'], ['c'], ['d'], ['a', 'b'], ['b', 'c'], ['c', 'd'], ['a', 'b', 'c', 'd']]
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • This is almost there, but need it to be in square brackets, do you have a link where you learnt how to do this or was it experience? – Shikari Jan 06 '21 at 16:21
  • You can learn more about pairwise iteration here: https://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list. It's not exactly what you asked for, because you also need individual elements, but it's an abstraction of the 3rd line in the function I wrote here. Changing to square brackets (lists) instead of parenthesis (tuples) is just mapping `list` over the results of `zip`. – g.d.d.c Jan 06 '21 at 16:25