Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

python - Finding particular outcomes of sub-lists

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...