python - 无重复排列
问题描述
我正在寻找一个简单的命令/函数来生成作为 shell 命令的参数给出的数字集的排列。
在此示例中,我可以在 Python 中从 1-6 个数字生成所有 6 个数字排列:
root@debian:~# python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import permutations
>>> perm = permutations([1, 2, 3, 4, 5, 6], 6)
>>> for i in list(perm):
... print i
...
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 6, 5)
(1, 2, 3, 5, 4, 6)
(1, 2, 3, 5, 6, 4)
(1, 2, 3, 6, 4, 5)
(1, 2, 3, 6, 5, 4)
(1, 2, 4, 3, 5, 6)
[...]
如何以更简单的方式做到这一点,最好使用单行命令,其中可以提供所有此类数字作为参数,例如:
$ command 1 2 3 4 5 6
预期输出为:
1 2 3 4 5 6
1 2 3 4 6 5
1 2 3 5 4 6
1 2 3 5 6 4
1 2 3 6 4 5
1 2 3 6 5 4
1 2 4 3 5 6
[...]
更新:当脚本使用参数时,只打印出一行:
root@debian:~# cat permut.py
import sys
n1 = sys.argv[1]
n2 = sys.argv[2]
n3 = sys.argv[3]
n4 = sys.argv[4]
n5 = sys.argv[5]
n6 = sys.argv[6]
from itertools import combinations
comb = combinations([sys.argv[1], n2, n3, n4, n5, n6], 6)
for i in list(comb):
print i
root@debian:~# python permut.py 1 2 3 4 5 6
('1', '2', '3', '4', '5', '6')
root@debian:~#
虽然在 scipt 中提供数字时效果很好,但为什么呢?
root@debian:~# cat permut2.py
from itertools import permutations
perm = permutations([21, 2, 30, 34, 15, 46], 6)
for i in list(perm):
print i
root@debian:~# python permut2.py|head -10
(21, 2, 30, 34, 15, 46)
(21, 2, 30, 34, 46, 15)
(21, 2, 30, 15, 34, 46)
(21, 2, 30, 15, 46, 34)
(21, 2, 30, 46, 34, 15)
(21, 2, 30, 46, 15, 34)
(21, 2, 34, 30, 15, 46)
(21, 2, 34, 30, 46, 15)
(21, 2, 34, 15, 30, 46)
(21, 2, 34, 15, 46, 30)
也与“int(sys.argv)”不起作用:
root@debian:~# cat permut.py
import sys
n1 = int(sys.argv[1])
n2 = int(sys.argv[2])
n3 = int(sys.argv[3])
n4 = int(sys.argv[4])
n5 = int(sys.argv[5])
n6 = int(sys.argv[6])
from itertools import combinations
comb = combinations([n1, n2, n3, n4, n5, n6], 6)
for i in list(comb):
print i
root@debian:~# python permut.py 1 2 3 4 5 6
(1, 2, 3, 4, 5, 6)
root@debian:~#
解决方案
获取命令行参数列表,并为此列表的每个排列显示用空格分隔的单个值。
import itertools
import sys
for p in itertools.permutations(sys.argv[1:]):
print(" ".join(p))
推荐阅读
- excel - 我可以将 Excel 按钮与一行相关联,以便它们可以包含在排序/过滤器中吗?
- css - 当 :host 可以满足 Angular 的需求时,为什么需要 :host-context
- bash - 管道输出从命令到另一个命令
- react-native - 无法在反应原生项目上执行 npm install
- php - 将配置文件从 Google Cloud Storage 提取到 App Engine Standard 的选项有哪些?
- maven - Arquillian 未部署在 Weblogic 12c 远程服务器中
- c - STM32F4如何写一个时差函数
- netty - 在实例字段中存储状态的 ChannelHandler 和使用属性的 ChannelHandler 有什么区别?
- google-maps - 如何在地图圆形图像或带有图像的圆形标记中显示?
- reactjs - 用酶和玩笑测试反应应用程序 - 查找方法的问题