Reputation: 1787
Having the following list of lists ['boundari', 'special', ['forest', 'arb'], 'abod']
, I would like to obtain the the following combination:
[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]
The nearest solution applying the next product when removing the last item abod
(which I need to keep):
print([list(p) for p in product([toks[:2]], *toks[2:])])
[[['boundari', 'special'], 'forest'], [['boundari', 'special'], 'arb']]
However, I have not obtained the correct combination:
[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]
Upvotes: 2
Views: 77
Reputation: 2163
Another solution using only simple loops would be something like this and in case order of lists inside is not important:
my_list_of_list = ['boundari', 'special', ['forest', 'arb'], 'abod']
indecies_of_lists = []
base_list = []
lists_of_lists = []
output = []
for item in my_list_of_list:
if type(item) == list:
lists_of_lists.append(item)
else:
base_list.append(item)
for item in lists_of_lists:
for sub_item in item:
new_list = list(base_list)
new_list.append(sub_item)
output.append(new_list)
print(output)
output will be [['boundari', 'special', 'abod', 'forest'], ['boundari', 'special', 'abod', 'arb']]
Upvotes: 1
Reputation: 4630
You can do something like this:
arr = ['boundari', 'special', ['forest', 'arb'], 'abod']
def get_combinations(arr):
n = len(arr)
def _get_combinations(so_far, idx):
if idx >= n:
yield so_far[:]
return
if isinstance(arr[idx], list):
for val in arr[idx]:
so_far.append(val)
yield from _get_combinations(so_far, idx + 1)
so_far.pop()
else:
so_far.append(arr[idx])
yield from _get_combinations(so_far, idx + 1)
so_far.pop()
yield from _get_combinations([], 0)
expected_ans = [
['boundari', 'special', 'forest', 'abod'],
['boundari', 'special', 'arb', 'abod'],
]
assert list(get_combinations(arr)) == expected_ans
Upvotes: 2