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
233 views
in Technique[技术] by (71.8m points)

Find combinations of list in specific order Python

I have a list such as

descr_list = ["I","LOVE","DOGS"]

I want a loop that can create sub lists in the order below

["I","LOVE","DOGS"]
["I","LOVE"]
["I"]
["LOVE","DOGS"]
["LOVE"]
["DOGS"]

Here is the loop i currently have and i am getting the below output

for r in range(len(descr_list)):
    for j in range(r+1,len(descr_list)+1):
        result = descr_list[r:j]
        print(result)

['i']
['i', 'love']
['i', 'love', 'dogs']
['love']
['love', 'dogs']
['dogs']

Any help would be greatly appreciated. I know I've done this before but i just can't remember how i did it haha. I need to start at the first element(we can call x) in the list and it needs to read all elements after it. Then walk backwards by 1 element until it gets back to itself and then jump to the next element(x+1) and repeat the same process above until we reach the last element in the list.

question from:https://stackoverflow.com/questions/65943758/find-combinations-of-list-in-specific-order-python

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

1 Reply

0 votes
by (71.8m points)

You can use nested loops:

l = len(descr_list)
for i in range(l):
    for j in range(l, i, -1):
        print(f"{descr_list[i:j]} slice from {i} to {j}")

['I', 'LOVE', 'DOGS'] slice from 0 to 3
['I', 'LOVE'] slice from 0 to 2
['I'] slice from 0 to 1
['LOVE', 'DOGS'] slice from 1 to 3
['LOVE'] slice from 1 to 2
['DOGS'] slice from 2 to 3

I printed i and j for a better understanding.


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

...