Python:获取列表的可能性并更改循环数 [英] Python :get possibilities of lists and change the number of loops
问题描述
我希望能够更改循环数并将所有可能性存储在(列表列表)中.让我通过一个例子来解释:
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:
您有以下列表:
initial_list=[1,2]
然后您有一个参数n,即循环数
Then you have a parameter n, which is the number of loops
例如,如果n = 2,我希望我的程序返回此列表:
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]]
所以当 n=3 时,程序会对 3 'x' 做同样的事情
So for n=3, the program would do the same with 3 'x', etc
此外,我希望我的initial_list可以具有不同的长度,例如[1,2,3]或[1,2,3,4]等
Also, i'd like my initial_list could have different length, like [1,2,3] or [1,2,3,4], etc
如果参数n被硬编码(通过n循环),我知道该怎么做,但是如果n改变,是否可以这样做?
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 ^^
推荐答案
您可以使用递归函数:
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]]
工作方式:
- 您输入了原始列表和x的
n
的数量,以及一个空列表作为原始解决方案" - 它检查列表的长度或n是否大于0
- 如果不是,则返回当前解决方案
- 否则,它将添加到解决方案中,并返回到步骤2
- You input your original list and number of x's
n
, as well as an empty list as the original 'solution' - It checks if either the length of your list, or n is larger than 0
- If not, it returns the current solution
- Otherwise, it adds onto the solution, and goes back to step 2
这比排列的想法稍微复杂一些,但是,当您的列表或 n 变大时,这会快得多,因为您不必担心删除双打.
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.
这篇关于Python:获取列表的可能性并更改循环数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!