簡體   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