簡體   English   中英

如何在某些位置生成字符串的所有可能組合?

[英]How to generate all possible combinations of a string at certain positions?

我將如何獲取一個字符串並用字符列表的所有可能組合替換所有出現的給定字符?

例如 string = "GPxLEKxLExx",將 x 替換為 ['A','B','C','D','E','F']

這樣它就會返回:

GPALEKALEAA GPBLEKALEAA GPBLEKBLEAA ... GPFLEKALEAA ... GPFLEKFLEFF

以及這些字符的所有其他組合。

根據以下答案之一,這對我有用:

from itertools import product

input_str = 'GPxLEKxLExx'
input_str = input_str.replace('x', '{}')

outputs = []
for comb in product('ABCDEF', repeat=4):
    outputs.append(input_str.format(*comb))
from itertools import combinations_with_replacement

input_str = 'GPxLEKxLExx'
input_str = input_str.replace('x', '{}')

outputs = []
for comb in combinations_with_replacement(['A','B','C','D','E','F'], 4):
    outputs.append(input_str.format(*comb))

編輯:作為@Phossel指出,適當的功能是itertools.product代替combinations_with_replacement 所以為了清楚起見,固定版本是:

from itertools import product

input_str = 'GPxLEKxLExx'
input_str = input_str.replace('x', '{}')

outputs = []
for comb in product(['A','B','C','D','E','F'], repeat=4):
    outputs.append(input_str.format(*comb))
myString = "GPxLEKxLExx"
charList = [ 'A', 'B', 'C', 'D', 'E', 'F']
newList = []

for i in charList:
   newList.append(myString.replace("x",i))

newList 中的值是正確答案

你可以這樣做

from itertools import combinations
string = "GP{}LEK{}LE{}{}"
l= ['A','B','C','D','E','F']
l2=list(combinations(l, 4))
for i in l2:
    print(string.format(*i))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM