找到给定编号的所有可能排列和组合。使用 Python 的列表中的元素
Find all possible permutations and combinations of given no. of elements in a list using Python
我需要找到给定元素的所有可能排列和组合,而不重复相同的对。
例如
list = [a,b,c]
期望的输出是
[(a),(b),(c),(a,b),(a,c),(b,a),(b,c),(c,a),(c,b),(a,b,c),(a,c,b),(b,a,c),(b,c,a),(c,a,b),(c,b,a)]
我在 python 中尝试 itertools
以获得相同的输出对,但失败了。
使用 itertools.permutations
输出是
[abc,acb,bac,bca,cab,cba]
使用 itertools.combinations
输出是
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
错过了 (b,a)
这样的对
.
使用 itertools.combinations_with_replacement
给出对中的重复元素,例如(a,a,a),(b,b,b)
,这是不可接受的。
所需的输出不应包含重复的对元素。
answer = set()
L = ['a', 'b', 'c']
for i in range(len(L)+1):
for c in itertools.combinations(L, i):
for p in itertools.permutations(c):
answer.add(p)
In [288]: answer
Out[288]:
{(),
('a',),
('a', 'b'),
('a', 'b', 'c'),
('a', 'c'),
('a', 'c', 'b'),
('b',),
('b', 'a'),
('b', 'a', 'c'),
('b', 'c'),
('b', 'c', 'a'),
('c',),
('c', 'a'),
('c', 'a', 'b'),
('c', 'b'),
('c', 'b', 'a')}
permutations
允许您指定排列列表的长度:
如果包含空集:
permlist = []
for i in range(len(mylist) + 1):
permlist += itertools.permutations(mylist, i)
如果排除空集:
permlist = []
for i in range(len(mylist)):
permlist += itertools.permutations(mylist, i+1)
我需要找到给定元素的所有可能排列和组合,而不重复相同的对。
例如
list = [a,b,c]
期望的输出是
[(a),(b),(c),(a,b),(a,c),(b,a),(b,c),(c,a),(c,b),(a,b,c),(a,c,b),(b,a,c),(b,c,a),(c,a,b),(c,b,a)]
我在 python 中尝试 itertools
以获得相同的输出对,但失败了。
使用 itertools.permutations
输出是
[abc,acb,bac,bca,cab,cba]
使用 itertools.combinations
输出是
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
错过了 (b,a)
这样的对
.
使用 itertools.combinations_with_replacement
给出对中的重复元素,例如(a,a,a),(b,b,b)
,这是不可接受的。
所需的输出不应包含重复的对元素。
answer = set()
L = ['a', 'b', 'c']
for i in range(len(L)+1):
for c in itertools.combinations(L, i):
for p in itertools.permutations(c):
answer.add(p)
In [288]: answer
Out[288]:
{(),
('a',),
('a', 'b'),
('a', 'b', 'c'),
('a', 'c'),
('a', 'c', 'b'),
('b',),
('b', 'a'),
('b', 'a', 'c'),
('b', 'c'),
('b', 'c', 'a'),
('c',),
('c', 'a'),
('c', 'a', 'b'),
('c', 'b'),
('c', 'b', 'a')}
permutations
允许您指定排列列表的长度:
如果包含空集:
permlist = []
for i in range(len(mylist) + 1):
permlist += itertools.permutations(mylist, i)
如果排除空集:
permlist = []
for i in range(len(mylist)):
permlist += itertools.permutations(mylist, i+1)