Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sequential combined list in python?

I've got a list ['a', 'b', 'c', 'd'] and I need a list ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'].

I've been looking at itertools, but I'm not seeing how to make this work.

For all combinations, the code would be:

from itertools import permutations
stuff = ['a','b','c','d']
for i in range(0, len(stuff)+1):
    for subset in permutations(stuff, i):
           print(subset)

What would I need to do to return only sequential combinations? I guess I could check the order for each permutation as I go, but that doesn't seem to be the best way.

like image 247
Joseph Avatar asked Oct 02 '15 02:10

Joseph


People also ask

How do I make a list of sequential numbers in Python?

Python comes with a direct function range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use range() with r1 and r2 and then convert the sequence into list.

How do I combine multiple lists into one Python?

chain() method is passed the arguments of list1, list2 and list3. This method takes multiple arguments and returns a single sequence of items. So, the chain() method concatenates all three lists. The result of the method call is converted into a list using the list() method.

How do you create a list from 1 to 100 in Python?

Using the range() function to create a list from 1 to 100 in Python. In Python, we can use the range() function to create an iterator sequence between two endpoints. We can use this function to create a list from 1 to 100 in Python. The function accepts three parameters start , stop , and step .

How do you merge three lists in Python?

Using + operator The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.


1 Answers

Quite simply:

stuff = ['a','b','c','d']
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)])

Gives

['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
like image 111
njzk2 Avatar answered Sep 23 '22 21:09

njzk2