从 2 个列表生成所有交换的集合
我使用Pyhton,想创建类似一组列表的东西。我解释。 作为输入,我有这样的列表:
s = [[0,4,5,6,8],[1,2,3]]
我想在所有s [0]和s [1]元素之间对此进行随机交换。问题在于我想枚举(不明确)此交换的所有可能结果。我尝试了一些Itertools的东西,但没有成功。 换句话说,预期的输出是一个可达的,包含s的所有可能交换。 欢迎任何建议!
s = [[0,4,5,6,8],[1,2,3]]
def swap(s):
i0 = randint(0,len(s[0])-1)
i1 = randint(0,len(s[1])-1)
s[0][i0],s[1][i1] = s[1][i1],s[0][i0]
编辑:我认为我没有很好地解释问题。 如果我们有输入:
s = [[0,4,5,6,8],[1,2,3]]
ouput将是类似的:
S = [[[1,4,5,6,8],[0,2,3]],
[[0,1,5,6,8],[4,2,3]],
[[0,4,1,6,8],[5,2,3]],
[[0,4,5,1,8],[6,2,3]],
[[0,4,5,6,1],[8,2,3]],
[[2,4,5,6,8],[1,0,3]],
...
对于s中的每个元素e,e必须与s不同,则只有一个2个元素的置换
I use pyhton and would like to create something like a set of lists. I explain.
As input, I have a list like this :
s = [[0,4,5,6,8],[1,2,3]]
I want to apply random swap on this s between all s[0] and s[1] elements. The problem is that I want to kind of enumerate (not explicitly) all the possible results of this swap. I have try some itertools stuff but didn't success.
In other words, the expected output is an iterable containing all possible swap from s.
Any advice is welcome !
s = [[0,4,5,6,8],[1,2,3]]
def swap(s):
i0 = randint(0,len(s[0])-1)
i1 = randint(0,len(s[1])-1)
s[0][i0],s[1][i1] = s[1][i1],s[0][i0]
Edit : I think I did not explain well the problem.
If we have as input :
s = [[0,4,5,6,8],[1,2,3]]
The ouput would be something like :
S = [[[1,4,5,6,8],[0,2,3]],
[[0,1,5,6,8],[4,2,3]],
[[0,4,1,6,8],[5,2,3]],
[[0,4,5,1,8],[6,2,3]],
[[0,4,5,6,1],[8,2,3]],
[[2,4,5,6,8],[1,0,3]],
...
For each element e in S, e must be different from s by only one permutation of 2 elements
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定我是否正确地解决了您的问题,但是您可以使用 itertools.combinations 用于生成所有可能的掉期。
对于您的示例,结果列表包含所有15个可能的单swaps。
这里的摘录:
Not sure if I get your question right, but you can use itertools.combinations for generating all possible swaps.
For your example the result list contains all 15 possible single-swaps.
Here an extract:
也许我误解了这个问题,但是如果您希望所有组合将列表1的元素与列表2的元素交换为2。我们创建了嵌套列表的副本并在这两个列表中的份量中删除元素,这是另一种方法
。
输出:
Maybe I misunderstood the question, but here is another way to do so if you want all combinations swapping an element of list 1 with an element of list 2.
We create a copy of the nested list and permute elements in those two lists.
Output: