删除其中有两个连续元音的单词

我想要的是删除其中有两个以上连续元音的单词。所以输入:

s = " There was a boat in the rain near the shore, by some mysterious lake"

输出:

[boat,rain,near,mysterious]

这是我的代码。我只是想知道是否有更好的方法可以做到这一点,或者它是否足够有效?是否可以使用python

dict做到这一点,还是列表可以?:)我是python的新手,是的。:)评论会很好。

def change(s):

vowel = ["a","e","i","o","u"]

words = []

a = s[:].replace(",","").split()

for i in vowel:

s = s.replace(i, "*").replace(",","")

for i,j in enumerate(s.split()):

if "**" in j:

words.append(a[i])

return words

回答:

使用集:

使用set.intersection的第一种方法只能找到不相同的连续对,因此oo不会是匹配项:

s = " There was a boat in the rain near the shore, by some mysterious lake"

vowels = "aeiouAEIOU"

print([x for x in s.split() if any(len(set(x[i:i+2]).intersection(vowels))== 2 for i in range(len(x))) ])

['boat', 'rain', 'near', 'mysterious']

方法2使用set.issubset,因此现在将相同的连续对视为匹配。

使用set.issubset与函数使用yield from蟒3语法,这可能是更合适的,并确实捕捉重复相同元音:

vowels = "aeiouAEIOU"

def get(x, step):

yield from (x[i:i+step] for i in range(len(x[:-1])))

print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in get(x, 2))])

或再次在单个列表中:

print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in (x[i:i+2] for i in range(len(x[:-1]))))])

最后,将元音设为一个集合,并检查它是否为任何字符对的set.issuperset:

vowels = {'a', 'u', 'U', 'o', 'e', 'i', 'A', 'I', 'E', 'O'}

def get(x, step):

yield from (x[i:i+step] for i in range(len(x[:-1])))

print([x for x in s.split() if any(vowels.issuperset(pr) for pr in get(x, 2))])

以上是 删除其中有两个连续元音的单词 的全部内容, 来源链接: utcz.com/qa/403350.html

回到顶部