Python :get possibilities of lists and change the number of loops

情到浓时终转凉″ 提交于 2021-02-10 19:53:28

问题


I'd like to be able to change the number of loops and store all possibilities in a (list of lists). Let me explain by an example:

You have the following list:

 initial_list=[1,2]

Then you have a parameter n, which is the number of loops

For example if n=2, I'd like my programm to return this list:

 final_list=[[x,x,1,2],[x,1,x,2],[x,1,2,x],[1,x,x,2],[1,x,2,x][1,2,x,x]]

So for n=3, the program would do the same with 3 'x', etc

Also, i'd like my initial_list could have different length, like [1,2,3] or [1,2,3,4], etc

I know how to do that if the parameter n is hardcoded ( by n loop) but is it possible to do that if n change?

Thanks and sorry for my bad explaination ^^


回答1:


You can do this with a recursive function:

def get_lists(lst, n, sol):
    if len(lst) == 0 and n == 0:
        return [sol]
    solutions = []
    if len(lst) > 0:
        solutions += get_lists(lst[1:], n, sol + [lst[0]])
    if n > 0:
        solutions += get_lists(lst, n - 1, sol + ['x'])
    return solutions

n = 2
initial_list = [1, 2]
print(get_lists(initial_list, n, []))
>>> [[1, 2, 'x', 'x'], [1, 'x', 2, 'x'], [1, 'x', 'x', 2], ['x', 1, 2, 'x'], ['x', 1, 'x', 2], ['x', 'x', 1, 2]]

The way it works:

  1. You input your original list and number of x's n, as well as an empty list as the original 'solution'
  2. It checks if either the length of your list, or n is larger than 0
  3. If not, it returns the current solution
  4. Otherwise, it adds onto the solution, and goes back to step 2

This is slightly more complicated than the permutations idea, however, when your list or n becomes large, this will be much faster because you won't have to worry about removing doubles.




回答2:


Use itertools.permutations:

import itertools

def permutations(initial_list, n, x):
    return list(itertools.permutations(initial_list + [x] * n))



回答3:


You could let itertools.combinations give you indexes where to insert 'x':

for indexes in combinations(range(len(initial_list) + n), n):
    tmp = initial_list[:]
    for i in indexes:
        tmp.insert(i, 'x')
    print(tmp)

Output:

['x', 'x', 1, 2]
['x', 1, 'x', 2]
['x', 1, 2, 'x']
[1, 'x', 'x', 2]
[1, 'x', 2, 'x']
[1, 2, 'x', 'x']


来源:https://stackoverflow.com/questions/59829811/python-get-possibilities-of-lists-and-change-the-number-of-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!