Home > Blockchain >  How to return all sub-list from list that contains lists
How to return all sub-list from list that contains lists

Time:12-29

There is a list in python l1 =['the movie is',['good','bad'],'and it was',['nice','not bad']] So I want The output:

Output:
the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad

How Can I do it?

CodePudding user response:

You can do it in one line if you change the single elements to a list as well.

from itertools import product

l1 = ['the movie is', ['good','bad'], 'and it was', ['nice','not bad']]
l1 = [item if isinstance(item, list) else [item] for item in l1]

# finding all combinations
all_combinations = [' '.join(item) for item in product(*l1)]

print(all_combinations)

Output:
[
    'the movie is good and it was nice',
    'the movie is good and it was not bad',
    'the movie is bad and it was nice',
    'the movie is bad and it was not bad'
]

The first line takes care of converting single elements to a list.

CodePudding user response:

You can iterate over the list and check the type of each element. If the element is a string, you just need to append it, but if it is a sublist, you need to generate a combination for each string in the sublist.

The following code does the job:

def get_all_combinations(input_list):

    # Start with a single empty list
    combinations = [[]]

    for e in input_list:
        # If next element in main list is a string, append that string to
        # all combinations found so far
        if isinstance(e, str):
            combinations = [c   [e] for c in combinations]
        # If next element in main list is a sublist, add each strings in
        # sublist to each combination found so far
        elif isinstance(e, list):
            combinations = [c   [e2] for c in combinations for e2 in e]

    # Join all lists of strings together with spaces
    combinations = [' '.join(c) for c in combinations]

    return combinations
    

l1 =['the movie is',['good','bad'],'and it was',['nice','not bad']]

l1_combinations = get_all_combinations(l1)
for combination in l1_combinations:
    print(combination)

Output:

the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad

CodePudding user response:

This will do it:

x = 0
while x < 2:
  for a in l1[3]:
    print(f"{l1[0]} {l1[1][x]} {l1[2]} {a}")
  x = x   1



Output:
the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad
  • Related