如何通过重复生成所有排列/使函数嵌套 x 量
How to generate all permutations with repetitions /make x amount of nested for functions
我正在尝试为我的脚本创建一个函数来生成所有可能的重复排列。我不能使用任何导入模块,所以没有 itertools。 (它是一个解决 FLP 问题的项目,明确说明没有 itertools)。
基本上,我想要这个功能。
它应该接受两个参数,包含要从中取出的对象的列表,以及可以取出的对象的数量。
例如可取物个数为3,取物ListA个为[0,1,2,3],则函数应该几乎执行以下代码或输出相同的结果。
res = []
for i in ListA:
for x in ListA:
for y in ListA:
res.append([i,x,y])
return res
我只是不知道如何在 python 中实现 X 数量的嵌套 for 函数。有人可以帮助我或指出正确的方向吗
ListA = [0, 1, 2, 3]
n = 3
def func(ListA, n):
res = [[l] for l in ListA]
for i in range(n-1):
res = [r+[l] for r in res for l in ListA]
return res
res_Michael = func(ListA, n)
res = []
for i in ListA:
for x in ListA:
for y in ListA:
res.append([i, x, y])
print(res_Michael == res)
# True
res = [[l] for l in ListA]
初始化列表如下:
[[0], [1], [2], [3]]
我们需要对元素进行迭代,稍后再进行连接:
[ [0, 0], ..., [0, 3],
[1, 0], ..., [1, 3], ...
]
for i in range(n-1):
因为res已经初始化了,所以我们只concat (n-1) times
res = [r+[l] for r in res for l in ListA]
r+[l]
type of r is list
r+[l]
表示 concat list r and [l]
l 是 ListA 中的 number
,
所以
[l]
是a list with only one element
for r in res for l in ListA
你的输出是:
[0, 0, 0] then [0, 0, 1]
不是:
[0, 0, 0] then [1, 0, 0]
所以如果不会 for l in ListA for r in res
就是这些
我正在尝试为我的脚本创建一个函数来生成所有可能的重复排列。我不能使用任何导入模块,所以没有 itertools。 (它是一个解决 FLP 问题的项目,明确说明没有 itertools)。
基本上,我想要这个功能。
它应该接受两个参数,包含要从中取出的对象的列表,以及可以取出的对象的数量。
例如可取物个数为3,取物ListA个为[0,1,2,3],则函数应该几乎执行以下代码或输出相同的结果。
res = []
for i in ListA:
for x in ListA:
for y in ListA:
res.append([i,x,y])
return res
我只是不知道如何在 python 中实现 X 数量的嵌套 for 函数。有人可以帮助我或指出正确的方向吗
ListA = [0, 1, 2, 3]
n = 3
def func(ListA, n):
res = [[l] for l in ListA]
for i in range(n-1):
res = [r+[l] for r in res for l in ListA]
return res
res_Michael = func(ListA, n)
res = []
for i in ListA:
for x in ListA:
for y in ListA:
res.append([i, x, y])
print(res_Michael == res)
# True
res = [[l] for l in ListA]
初始化列表如下:
[[0], [1], [2], [3]]
我们需要对元素进行迭代,稍后再进行连接:
[ [0, 0], ..., [0, 3],
[1, 0], ..., [1, 3], ...
]
for i in range(n-1):
因为res已经初始化了,所以我们只concat (n-1) times
res = [r+[l] for r in res for l in ListA]
r+[l]
type of r is list
r+[l]
表示 concat list r and [l]
l 是 ListA 中的 number
,
所以
[l]
是a list with only one element
for r in res for l in ListA
你的输出是:
[0, 0, 0] then [0, 0, 1]
不是:
[0, 0, 0] then [1, 0, 0]
所以如果不会 for l in ListA for r in res
就是这些