gpt4 book ai didi

python - 附加到 Python 列出每个列表项的所有可能转换

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:47 26 4
gpt4 key购买 nike

我有一个可能的密码列表,我需要在此列表中附加每个密码的简单转换。说我的 list 是

['sauce', 'banana']

这里显示了一系列转换。

'a'-->'@'

的'-->'$'

然后我想将所有可能的转换添加到列表中。所以现在列表应该看起来像

['$auce', 's@uce', '$@uce', 'b@nana', 'ban@na',
'banan@', 'b@n@na', 'b@nan@,' 'ban@n@', 'b@n@n@']

我如何在 Python 中做到这一点?

我首先尝试创建一个进行所有转换的函数。然后我把那个转换后的字符串和原始字符串做了一个叉积。然而,这会导致很多重复,而且看起来有点 hacky。

函数:

def symbolize(s):
options = {
'a': '@',
'S': '$'
}
copy = ''
for i in range(len(s)):
if s[i] in options:
copy += options[s[i]]
else:
copy += s[i]
return copy

然后是叉积:

for x in range(len(candidates)):
candidates += list(''.join(t) for t in itertools.product(
*zip(candidates[x], symbolize(candidates[x]))))

最佳答案

from itertools import product

def all_versions_of_word(word, alt_chars, skip_orig=True):
chars = [ch + alt_chars.get(ch, "") for ch in word]
combos = product(*chars)
if skip_orig and word: next(combos) # drop the first item
return ("".join(c) for c in combos)

def transform_passwords(passwords, alt_chars={"a":"@", "s":"$"}):
for word in passwords:
yield from all_versions_of_word(word, alt_chars)

运行方式如下

>>> list(transform_passwords(['sauce', 'banana']))
['s@uce',
'$auce',
'$@uce',
'banan@',
'ban@na',
'ban@n@',
'b@nana',
'b@nan@',
'b@n@na',
'b@n@n@']

关于python - 附加到 Python 列出每个列表项的所有可能转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com