[英]List of possible combinations of characters with OR statement
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). 我设法生成了一个字符'a','b'和'c'的所有可能组合的列表(下面的代码)。 Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. 现在我想添加第四个字符,可以是“d”或“f”,但不能同时使用两个字符。 How could I achieve this ? 我怎么能实现这个目标?
items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
print(p)
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
Created a new list items2
for d
and f
. 为d
和f
创建了一个新列表items2
。 Assuming that OP needs all combinations of [a,b,c,d]
and [a,b,c,f]
假设OP需要[a,b,c,d]
和[a,b,c,f]
所有组合
items1 = ['a', 'b', 'c']
items2 = ['d','f']
from itertools import permutations
for x in items2:
for p in permutations(items1+[x]):
print(p)
A variation on @Van Peer's solution. @Van Peer解决方案的变体。 You can modify the extended list in-place: 您可以就地修改扩展列表:
from itertools import permutations
items = list('abc_')
for items[3] in 'dg':
for p in permutations(items):
print(p)
itertools.product
is suitable for representing these distinct groups in a way which generalizes well. itertools.product
适合以一种很好地概括的方式表示这些不同的组。 Just let the exclusive elements belong to the same iterable passed to the Cartesian product. 只需将独占元素属于传递给笛卡尔积的同一迭代。
For instance, to get a list with the items you're looking for, 例如,要获取包含您要查找的项目的列表,
from itertools import chain, permutations, product
list(chain.from_iterable(map(permutations, product(*items, 'df'))))
# [('a', 'b', 'c', 'd'),
# ('a', 'b', 'd', 'c'),
# ('a', 'c', 'b', 'd'),
# ('a', 'c', 'd', 'b'),
# ('a', 'd', 'b', 'c'),
# ('a', 'd', 'c', 'b'),
# ('b', 'a', 'c', 'd'),
# ('b', 'a', 'd', 'c'),
# ('b', 'c', 'a', 'd'),
# ('b', 'c', 'd', 'a'),
# ('b', 'd', 'a', 'c'),
# ('b', 'd', 'c', 'a'),
# ('c', 'a', 'b', 'd'),
# ('c', 'a', 'd', 'b'),
# ...
like this for example 比如这样
items = ['a', 'b', 'c','d']
from itertools import permutations
for p in permutations(items):
print(p)
items = ['a', 'b', 'c','f']
from itertools import permutations
for p in permutations(items):
print(p)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.