Python 如何在一个数组中组合两个文本
我只是做这个循环来检测“元音”数组中的“a”,并且只有一个空格 像'a'=1个空间,'ant'=3个空间 我想在数组中将“a”与下面的单词组合起来 如何将'a'与'ir'组合,使'word'数组成为Python 如何在一个数组中组合两个文本,python,Python,我只是做这个循环来检测“元音”数组中的“a”,并且只有一个空格 像'a'=1个空间,'ant'=3个空间 我想在数组中将“a”与下面的单词组合起来 如何将'a'与'ir'组合,使'word'数组成为 vowels=["a","e","i","o","u"] word=["a","ir","the","book"] for i in word: if len(i) == 1 and i in vowels: .... 注:向后迭代;否则,只要调用list.pop,索引就会
vowels=["a","e","i","o","u"]
word=["a","ir","the","book"]
for i in word:
if len(i) == 1 and i in vowels:
....
注:向后迭代;否则,只要调用
list.pop
,索引就会被破坏。您可以使用迭代器来构造新列表,如果当前项是元音中的,只需添加next()
项,例如:
>>> vowels = {'a', 'e', 'i', 'o', 'u'} # used set for efficient `in` operation
>>> words = ['a', 'ir', 'the', 'book']
>>> for i in range(len(words) - 2, -1, -1):
... if words[i] in vowels:
... # len(words[i]) == 1 is redundant (all vowels items' length = 1)
... words[i] += words.pop(i + 1) # merge vowel with next word
...
>>> words
['air', 'the', 'book']
或者,如果您碰巧需要添加多个元音:
>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> words = ["a", "ir", "the", "book"]
>>> iterable = iter(word)
>>> [i+next(iterable, '') if i in vowels else i for i in iterable]
['air', 'the', 'book']
我不明白你的问题。@AChampion,我提出了一个与你类似的解决方案(iter+next
),但我遇到了一个案例的问题:word=['banan','a']
。您可以编写next(iterable,”)
来解决StopIteration问题。@AChampion,有一种情况下,您的解决方案和我的不一致:word=['a','i','r']
事实上,从OP的示例中不清楚这是否是他们需要解释的问题。虽然一个简单的递归帮助函数来执行concat
会使它在功能上等效。@AChampion,我最初提出了,尝试使用itertools.takewhile
代替递归;发现takewhile
放弃不匹配项。贴出这个答案:|什么是-2,-1,-1)?
>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> words = ["a", "ir", "the", "book"]
>>> iterable = iter(word)
>>> [i+next(iterable, '') if i in vowels else i for i in iterable]
['air', 'the', 'book']
def concat(i, iterable):
return i + concat(next(iterable, ''), iterable) if i in vowels else i
>>> words = ['a', 'i', 'r']
>>> iterable = iter(words)
>>> [concat(i, iterable) for i in iterable]
['air']