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

后端 未结 2 876
野趣味
野趣味 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']
    

提交回复
热议问题