Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 在迭代时将元素插入列表_Python 2.7 - Fatal编程技术网

Python 2.7 在迭代时将元素插入列表

Python 2.7 在迭代时将元素插入列表,python-2.7,Python 2.7,我知道这个问题已经被问了很多次了。我理解为什么修改我正在迭代的列表不起作用。我提出了一个想法,但我希望得到关于它是否会破裂的反馈,以及它可能是一种更好的、也许更像蟒蛇的方式。我想取一个字符串,每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, l

我知道这个问题已经被问了很多次了。我理解为什么修改我正在迭代的列表不起作用。我提出了一个想法,但我希望得到关于它是否会破裂的反馈,以及它可能是一种更好的、也许更像蟒蛇的方式。我想取一个字符串,每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”的长度仍然在变化,我不知道这会有什么帮助

提前感谢,, Adrian

使用和
生成
,您的代码可以按如下方式更改:

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