如何更有效地将字符串中的多个字符映射到单个字符?

2024-07-05 14:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种更有效的方法来将字符串中的多个字符替换为单个字符。在

目前,我的代码与以下类似:

example = 'Accomodation'

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

output = ''
for char in example:
    if char in VOWELS:
        output += 'v'
    elif char in VOWELS.upper():
        output += 'V'
    elif char in CONSONANTS:
        ....

在本例中,它最终将返回Vccvcvcvcvvc。在

我想提高效率的部分是:

^{pr2}$

理想情况下,该解决方案允许将字符字典映射为键,其值是选项列表。E、 g

replace_dict = {'v': VOWELS,
                'V': VOWELS.upper(),
                'c': CONSONANTS,
                ...

不幸的是,我对map不太熟悉,但我希望解决方案能够以某种方式利用它。在

研究

我发现了一个类似的问题:python replace multiple characters in a string

这意味着我必须做一些类似的事情:

target = 'Accomodation'
charset = 'aeioubcdfghjklmnpqrstvwxyzAEIOUBCDFGHJKLMNPQRSTVWXYZ'
key = 'vvvvvcccccccccccccccccccccVVVVVCCCCCCCCCCCCCCCCCCCCC'

对我来说,问题是赋值看起来不是特别清楚——尽管它保存了if/else语句块。另外,如果我想添加更多的字符集,赋值的可读性会越来越低,例如对于不同的外来字符集。在


任何人,也许对内置函数有更广泛的知识,能写出一个比上面两个例子更有效/更干净的例子吗?在

我也愿意接受其他不需要使用字典的想法。在

解决方案应该在python3。在


Tags: inoutputif字典example解决方案字符upper
3条回答

这是一种使用dict的方法。在

例如:

example = 'Accomodation'

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

replace_dict = {'v': VOWELS,
                "V": VOWELS.upper(),
                "c": CONSONANTS
                }


print("".join(k for i in example 
              for k, v in replace_dict.items() if i in v
              )
        )

输出:

^{pr2}$

有更有效的方法来创建这样的dict:

example = 'Accomodation'

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

replace_dict = {
    **{v: 'v' for v in VOWELS},
    **{V: 'V' for V in VOWELS.upper()},
    **{c: 'c' for c in CONSONANTS}
}

print(''.join(replace_dict[s] for s in example))

# Vccvcvcvcvvc

你的replace_dict想法很接近,但最好是“把”这句话“翻出来”,即把它从{'v': 'aei', 'c': 'bc'}变成{}。在

def get_replace_map_from_dict(replace_dict):
    replace_map = {}
    for cls, chars in replace_dict.items():
        replace_map.update(dict.fromkeys(chars, cls))
    return replace_map


def replace_with_map(s, replace_map):
    return "".join(replace_map.get(c, c) for c in s)


VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"


replace_map = get_replace_map_from_dict(
    {"v": VOWELS, "V": VOWELS.upper(), "c": CONSONANTS}
)
print(replace_with_map("Accommodation, thanks!", replace_map))

上面的replace_with_map函数保留了所有未映射的字符(但是您可以使用第二个参数将其更改为.get()),因此输出为

Vccvccvcvcvvc, ccvccc!

相关问题 更多 >