我有这段文字,该文字在括号内用索引标注:
Michael(1) Wigglesworth,(2) like(3) Taylor(4) an(5) Englishborn(6),
Harvard-educated(7) Puritan(8) minister.(9)
这些信息(内容和索引):
*Deleted :
Wigglesworth - 2
like - 3
Taylor - 4
an - 5
Englishborn, - 6
*Added:
Wigglesworth, - 2
is - 3
a - 4
handsome - 5
men - 6
who - 7
is - 8
这将是更新的句子:
Michael Wigglesworth is a handsome men who is Harvard-educated Puritan minister.
我当时正在考虑使用LinkedList。您是否有实现此想法的想法?
答案 0 :(得分:1)
使用列表方法pop
和insert
可以更轻松地完成此操作。对于删除,您必须首先从较高的索引中删除,而对于插入,则必须首先从较低的索引中插入,以保持目标索引的准确性。另外,Python中的索引基数为0,因此您需要相应地调整输入索引。
string = 'Michael Wigglesworth, like Taylor an Englishborn, Harvard-educated Puritan minister.'
delete = [1, 2, 3, 4, 5]
add = {
1: 'Wigglesworth',
2: 'is',
3: 'a',
4: 'handsome',
5: 'men',
6: 'who',
7: 'is'
}
words = string.split()
for i in delete[::-1]:
words.pop(i)
for i, word in add.items():
words.insert(i, word)
print(' '.join(words))
这将输出:
Michael Wigglesworth is a handsome men who is Harvard-educated Puritan minister.