Home > other >  Merge sublist with each item of list
Merge sublist with each item of list

Time:01-08

I have a list of lists and I need to join them together with each item of list. See example below:

my_list = [1, [2, 3], [4, 5]]

Expected result:

['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']

I tried to write the logic but one or other items are always missing.

CodePudding user response:

def join_lists(result, prefix, items):
    if not items:
        result.append('.'.join(map(str, prefix)))
    else:
        for i, item in enumerate(items[0]):
            join_lists(result, prefix   [item], items[1:])
        join_lists(result, prefix, items[1:])

my_list = [1, [2, 3], [4, 5]]
result = []
join_lists(result, [1], my_list)
print(result)

will produce:

Output: ['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']

CodePudding user response:

result = []

def join_lists(prefix, items): for item in items: if isinstance(item, list): join_lists(prefix "." str(item[0]), item[1:]) else: result.append(prefix "." str(item))

join_lists("1", my_list[1:])

print(result)

  • Related