因此,我正在嘗試制作一個采用模式(例如:c**l)的 python 腳本,它將回傳字串的每次迭代(* = 字母表中的任何字符)...
所以,我們得到類似的東西:caal、cbal、ccal等等。我曾嘗試使用 itertools 庫的產品,但無法使其正常作業。所以 2 小時后,我決定轉向 Stack Overflow。
這是我當前的代碼。它不完整,因為我覺得卡住了
alphabet = list('abcdefghijklmnopqrstuvwxyz')
wildChar = False
tmp_string = ""
combinations = []
if '*' in pattern:
wildChar = True
tmp_string = pattern.replace('*', '', pattern.count('*') 1)
if wildChar:
tmp = []
for _ in range(pattern.count('*')):
tmp.append(list(product(tmp_string, alphabet)))
for array in tmp:
for instance in array:
combinations.append("".join(instance))
tmp = []
print(combinations)
uj5u.com熱心網友回復:
你可以試試:
from itertools import product
from string import ascii_lowercase
pattern = "c**l"
repeat = pattern.count("*")
pattern = pattern.replace("*", "{}")
for letters in product(ascii_lowercase, repeat=repeat):
print(pattern.format(*letters))
結果:
caal
cabl
cacl
...
czxl
czyl
czzl
uj5u.com熱心網友回復:
用 itertools.product
import itertools
import string
s = 'c**l'
l = [c if c != '*' else string.ascii_lowercase) for c in s]
out = [''.join(c) for c in itertools.product(*l)]
輸出:
>>> out
['caal',
'cabl',
'cacl',
'cadl',
'cael',
'cafl',
'cagl',
'cahl',
'cail',
'cajl'
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354285.html
上一篇:Swift全名陣列排序
