我知道很多次都会问过这个问题。我理解为什么修改我迭代的列表是行不通的。我提出了一个想法,但是我想要反馈它是否会破坏,以及更好的,也许更多的Pythonic方式可能会这样做。我想取一个字符串并在每3个单词中插入“like”这个词。
def hedge(string):
a = string.split()
keep_up = 0 # To 'keep up' with the changing length of a
for i in range(3, len(a), 3):
a.insert(i+keep_up, 'like')
keep_up += 1 # Add 1 to keep_up every time 'like' is added, because this
return ' '.join(a) # messes with the index
返回如下字符串:
他的手掌像汗水一样,膝盖微弱,像手臂一样沉重。就像已经像他的毛衣一样呕吐,就像妈妈的意大利面。创建一个新变量似乎可能不是最简单的方法。还有更好的方法吗?
注意:在得到这个解决方案之前,我尝试了几种不同方式的'a'副本,但由于'a'的长度仍然在变化,我没有看到它会有什么帮助。
提前致谢, 阿德里安
答案 0 :(得分:1)
使用enumerate
和yield
,您的代码可以更改如下:
def hedge(s):
for i, word in enumerate(s.split()):
if i > 0 and i % 3 == 0:
yield 'like'
yield word
sentence1 = "his palms are sweaty, knees weak, arms are heavy. there's vomit on his sweater already, mom's spaghetti."
sentence2 = "his palms are like sweaty, knees weak, like arms are heavy. like there's vomit on like his sweater already, like mom's spaghetti."
assert ' '.join(hedge(sentence1)) == sentence2