How to find all possible combinations from nested list containing list and strings?

后端 未结 2 838
野趣味
野趣味 2021-01-20 00:21

I am trying to get all possible pattern from list like:

input_x = [\'1\', [\'2\', \'2x\'], \'3\', \'4\', [\'5\', \'5x\']]

As we see, it has

相关标签:
2条回答
  • 2021-01-20 01:18

    If you don't want to convert your list to all sub list then You can try something like this :

    input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x'],['6','6x']]
    
    import itertools
    non_li=[]
    li=[]
    for i in input_x:
        if isinstance(i,list):
            li.append(i)
        else:
            non_li.append(i)
    
    
    
    for i in itertools.product(*li):
        sub=non_li[:]
        sub.extend(i)
        print(sorted(sub))
    

    output:

    ['1', '2', '3', '4', '5', '6']
    ['1', '2', '3', '4', '5', '6x']
    ['1', '2', '3', '4', '5x', '6']
    ['1', '2', '3', '4', '5x', '6x']
    ['1', '2x', '3', '4', '5', '6']
    ['1', '2x', '3', '4', '5', '6x']
    ['1', '2x', '3', '4', '5x', '6']
    ['1', '2x', '3', '4', '5x', '6x']
    
    0 讨论(0)
  • 2021-01-20 01:23

    One way to achieve this is via using itertools.product. But for using that, you need to firstly wrap the single elements within your list to another list.

    For example, firstly we need to convert your list:

    ['1', ['2', '2x'], '3', '4', ['5', '5x']]
    

    to:

    [['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
    

    This can be done via below list comprehension as:

    formatted_list = [(l if isinstance(l, list) else [l]) for l in my_list]
    # Here `formatted_list` is containing the elements in your desired format, i.e.:
    #    [['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
    

    Now call itertools.product on the unpacked version of the above list:

    >>> from itertools import product
    
    #                v  `*` is used to unpack the `formatted_list` list
    >>> list(product(*formatted_list))
    [('1', '2', '3', '4', '5'), ('1', '2', '3', '4', '5x'), ('1', '2x', '3', '4', '5'), ('1', '2x', '3', '4', '5x')]
    
    0 讨论(0)
提交回复
热议问题