简体   繁体   English

Python:通过替换字符串的符号来创建字符串的所有派生词

[英]Python: create all derivatives of string by replacing its symbols

I've got some dict like that 我有这样的话

d = {'a' : ['1', '+', '='], 'b' : ['2'], c : ['3']}

My goal is to create a list of all possible derivatives from initial word by replacing its elements like that: 我的目标是通过替换这样的元素来创建初始单词所有可能衍生词的列表:

word = 'abcde'
rez = ['abcde', 
       '1bcde', '+bcde', '=bcde', 
       'a2cde', '12cde', '+2cde', '=2cde', 
       'ab3de', '1b3de', '+b3de', '=b3de', 'a23de', '123de', '+23de', '=23de']

Order of words in rez is not important. rez的单词rez并不重要。

I feel that there should be some easy way with itertools , but I can't see it. 我觉得itertools应该有一些简单的方法,但是我看不到。 Any nice and beautiful solution would be very welcome. 任何好的解决方案都将非常受欢迎。

Sure, itertools is always the answer for these kind of problems. 当然, itertools始终是此类问题的答案。 There may be better alternatives but the first that comes to my mind is using itertools.product : 可能有更好的选择,但我想到的第一个选择是使用itertools.product

from itertools import product

[''.join(chars) for chars in product(*[[x] + d.get(x, []) for x in word])]

Output 输出量

['abcde', 'ab3de', 'a2cde', 'a23de', '1bcde', '1b3de', '12cde', '123de',
 '+bcde', '+b3de', '+2cde', '+23de', '=bcde', '=b3de', '=2cde', '=23de']

Here is one approach. 这是一种方法。 Since you want to allow non-replacement (eg, leaving "a" as "a"), it is better to include the original character in the list of replacement values, so that the dict has, eg, 'a': ['a', '1', '+', '='] . 由于要允许非替换(例如,将“ a”保留为“ a”),最好将原始字符包括在替换值列表中,以便字典具有例如'a': ['a', '1', '+', '='] This can be done with: 这可以通过以下方式完成:

for k in d:
    d[k].append(k)

Then: 然后:

subs = [[(k, v) for v in vs] for k, vs in d.iteritems()]  
rez = []
for comb in itertools.product(*subs):
    baseword = word
    for before, after in comb:
        baseword = baseword.replace(before, after)
    rez.append(baseword)

The result: 结果:

['123de', '1b3de', '12cde', '1bcde', '+23de', '+b3de', '+2cde', '+bcde', '=23de', '=b3de', '=2cde', '=bcde', 'a23de', 'ab3de', 'a2cde', 'abcde']

Just for fun. 纯娱乐。 No import , no def , no indentation. import ,不def ,无压痕。

d = {'a' : ['1', '+', '='], 'b' : ['2'], 'c' : ['3']}
for key in d: d[key].append(key)
print reduce(lambda items, f: sum(map(f, items), []), [lambda msg, c=c: [msg.replace(c, r) for r in d[c]] for c in d.keys()], ["abcde"])

Result: 结果:

[
    '123de', '1b3de', '12cde', '1bcde', 
    '+23de', '+b3de', '+2cde', '+bcde', 
    '=23de', '=b3de', '=2cde', '=bcde', 
    'a23de', 'ab3de', 'a2cde', 'abcde'
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM