如何用Python列表推导式实现逐位删字符生成新字符串列表
问题:用Python列表推导式生成移除单个字符的字符串列表
需求:遍历单词中的每个字符,每次移除一个字符生成新字符串,输入'bathe'时,期望得到结果列表['athe', 'bthe', 'bahe', 'bate'](从左到右逐个移除前4个字符,若完整遍历所有字符则包含'bath')。
已尝试的代码
手动拼接方式
word = "bathe" newlist1 = [word[1::], (word[1:2] + word[-3:]), (word[:2] + word[-2:]), word[:3] + word[-1:] ] print('sample 1', newlist1) newlist2 = [(word[1:2] + word[-3:]), (word[1:2] + word[-3:]), (word[:2] + word[-2:]), word[:3] + word[-1:] ] print('sample 2', newlist2)
不符合预期的列表推导式
x = [(word[:i] + word[-j:]) for i in range(1,4) for j in range(4,1, -1)] # 输出结果为:['bathe', 'bthe', 'bhe', 'baathe', 'bathe', 'bahe', 'batathe', 'batthe', 'bathe']
正确的列表推导式实现
核心逻辑:对于字符串的每个索引i,将字符串拆分为i之前的部分和i+1之后的部分,拼接这两部分就得到移除第i个字符后的结果。
word = "bathe" # 遍历所有字符索引,生成完整的移除结果 full_result = [word[:i] + word[i+1:] for i in range(len(word))] print(full_result) # 输出: ['athe', 'bthe', 'bahe', 'bate', 'bath'] # 如果只需要前4个结果(对应移除前4个字符) partial_result = [word[:i] + word[i+1:] for i in range(len(word)-1)] print(partial_result) # 输出: ['athe', 'bthe', 'bahe', 'bate']
错误原因说明
之前的双重循环推导式错误地组合了i和j的取值,导致拼接后的字符串出现重复、多字符等问题,而正确的实现只需要单次遍历每个字符的索引,通过切片拼接即可完成需求。
内容的提问来源于stack exchange,提问作者gaurav8936
相关产品推荐
相关产品推荐

