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