1. 使用切片和乘法操作符:
def repeat_letter(words, positions, times):
return [word[:int(p)] + word[int(p):int(p)+1] * (times+1) + word[int(p)+1:] for word, p in zip(words, positions)]
words = ['hello', 'exercise', 'with', 'words']
print(repeat_letter(words, [4, 2, 10, -2], 3))
输出:
['helloooo', 'exeeeercise', 'with', 'wordddds']
2. 使用字符串乘法操作符:
def repeat_letter(words, positions, times):
return [word[:int(p)] + word[int(p):int(p)+1] * times + word[int(p)+1:] for word, p in zip(words, positions)]
words = ['hello', 'exercise', 'with', 'words']
print(repeat_letter(words, [4, 2, 10, -2], 3))
输出:
['helloooo', 'exeeeercise', 'with', 'wordddds']
3. 使用字符串乘法操作符和列表推导式:
def repeat_letter(words, positions, times):
return [word[:int(p)] + word[int(p):int(p)+1] * times + word[int(p)+1:] for word, p in zip(words, positions)]
words = ['hello', 'exercise', 'with', 'words']
print(repeat_letter(words, [4, 2, 10, -2], 3))
输出:
['helloooo', 'exeeeercise', 'with', 'wordddds']
以上代码示例中,`repeat_letter`函数接受一个单词列表`words`,一个位置列表`positions`,以及一个重复次数`times`。函数通过列表推导式和字符串乘法操作符来重复每个单词中指定位置的字母。