【问题标题】:Multi substitution on python listpython列表上的多重替换
【发布时间】:2021-09-01 04:36:22
【问题描述】:

我正在做一个破译秘密句子的项目。

当我输入 apple.appleapple.pear.orange.lemon

我希望它变成 A.B.E.R.T

我使用拆分和替换来做到这一点。但是,我找不到改变的方法 “苹果”变成 A 和 “苹果”变成B 同时因为当我使用replace()时,appleapple变成了AA 这是我尝试过的。


list1 = n.split()
list2 = f's.split([\\.]) : {list1}'

print(list2.replace("apple", "A"))
print(list2.replace("appleapple", "B"))
print(list2)

【问题讨论】:

  • 您可以将其更改为先替换appleapple,然后再替换apple

标签: python list replace


【解决方案1】:

我认为在这种情况下你应该使用字典而不是一直替换。如果您的项目的“词汇量”增加,您将很感激这样做。我会这样做:

dictionary = {
    'apple': 'A',
    'appleapple': 'B',
    'pear': 'E',
    'orange': 'R',
    'lemon': 'T'
}

original = 'apple.appleapple.pear.orange.lemon'
words_list = original.split('.')

result = [dictionary.get(word, 'unknown') for word in words_list]
result = '.'.join(result)

print(result)

上面会打印这个:

A.B.E.R.T

如果在您的词汇表中找不到所读单词,请注意使用字典的get() 方法添加默认值。例如,使用相同的字典和字符串apple.appleapple.pear.orange.lemon.otherthing(我在末尾添加了“其他”),我们将得到字符串A.B.E.R.T.unknown

【讨论】:

    【解决方案2】:

    你可以用字典代替

    secret_dict = {'apple':'A','appleapple':'B','pear':'E','orange':'R','lemon':'T'}
    n = 'apple.appleapple.pear.orange.lemon'
    words_in_n=n.split('.')
    resulting_secret_words = [secret_dict.get(word) for word in resulting_secret_words]
    secret_sentence = ''.join(resulting_secret_words)
    print(secret_sentence) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 2017-11-02
      • 2011-09-21
      • 1970-01-01
      • 2020-04-26
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多