繁体   English   中英

在 Python 中,创建用字符替换列表中最多 N 个位置的所有可能组合的最快方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM