[英]In Python, fastest way to create all possible combinations of replacing up to N positions in a list with a character
我有一个特定的用例,我需要创建包含字符串的列表的每个组合,最多用特定字符替换 N 个元素。 目前我正在生成每一个可能的组合,然后过滤哪些组合替换了少于 N 个元素,这不是很有效。
from itertools import product,repeat
l = ["A","B","C"]
n = 2
l_combs = list(set(product(*zip(l, repeat('')))))
l_combs
现在包含[('A', 'B', 'C'), ('A', 'B', ''), ('A', '', ''), ('', '', 'C'), ('', 'B', 'C'), ('', 'B', ''), ('', '', ''), ('A', '', 'C')]
l_wanted= [x for x in l_combs if x.count('') <= n)]
l_wanted
现在包含[('A', 'B', 'C'), ('A', 'B', ''), ('A', '', ''), ('', '', 'C'), ('', 'B', 'C'), ('', 'B', ''), ('A', '', 'C')]
如果列表l
包含许多元素,这可能非常有效。
在通用长度列表中生成替换元素最多 N 次的所有组合的有效方法是什么?
您所描述的是itertools.combinations
的行为,从索引总数中选择最多n
索引来替换项目,即列表l
的长度。 Map 索引组合以在输出时进行有效查找:
from itertools import combinations
l = ["A", "B", "C"]
n = 2
l_wanted = [
['' if i in c else v for i, v in enumerate(l)]
for k in range(n + 1) for c in map(set, combinations(range(len(l)), k))
]
l_wanted
变为:
[['A', 'B', 'C'], ['', 'B', 'C'], ['A', '', 'C'], ['A', 'B', ''], ['', '', 'C'], ['', 'B', ''], ['A', '', '']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.