python - 在 Python 中从数组中获取 1 元素交换的列表

标签 python arrays swap

从给定的数组中,我需要所有1-element-swap列表的列表。我不知道这怎么叫更好,如果我用一个例子来解释它。

例如。对于给定的数组:

数组 = [1,2,3,4]

我需要输出:

[2,1,3,4]
[3,2,1,4]
[4,2,3,1]
[1,3,2,4]
[1,4,3,2]
[1,2,4,3]

这意味着如果K是数组的大小,我必须得到(K(K-1))/2输出数组。

在上面的示例中,K=4 因此 4(3)/2=6 输出数组。

我真的不知道该怎么办。我知道有 itertools 函数,但是如果我使用 itertools.permutations(array) 我不会得到我想要的解决方案,因为这显示了我所有的排列,而且我只需要“1 个交换元素”列表的列表。

最佳答案

类似这样的事情应该可以帮助您开始:

>>> x = [1,2,3,4]
>>> for i in xrange(len(x)):
...     for j in xrange(i + 1, len(x)):
...         y = x[:]
...         y[i], y[j] = y[j], y[i]
...         print y
... 

关于python - 在 Python 中从数组中获取 1 元素交换的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609091/

相关文章:

python - 在 Python 中格式化聚合数据帧的 header

javascript - 如何从多个类(?)

python - 将来自 2 个字典的值组合成一个 np.array python

python - Pytest 模块未找到错误

python - 线程 : It is not safe to use pixmaps outside the GUI thread

python - 如何使用 Python matplotlib 在等高线图中绘制箭头和圆弧

c# - 将图像转换为字节流

visual-c++ - 如何交换 MFC CString?

Python 值交换什么都不做

c - 在 x86 汇编中交换 2 个整数