vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
我试图创建一个只返回常量的函数,然后是列表中的元音。
例如:
f("therapist")
>>>["he", "ra", "pi"]
f("apple")
>>>["le"]
所以只有当一个元音跟随一个辅音并且它在一个列表中返回辅音和元音时才会这样。
我认为这将是:
def f(word):
for consonant in word:
for vowel in word:
但我不知道如何处理订单并测试元音是否在辅音之后。提前致谢
答案 0 :(得分:4)
你可以使用起始索引为1的enumerate,检查当前的ele是否是辅音而下一个chaarcter word[i]
是元音。
def f(word):
vowels = {"a", "e", "i", "o", "u"}
consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
return [ele + word[i] for i, ele in enumerate(word[:-1], 1)
if word[i] in vowels and ele in consonants ]
或者使用循环跟踪最后一个字符并进行比较:
def f(word):
vowels = {"a", "e", "i", "o", "u"}
consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
pairs = []
it = iter(word)
# get first char
prev = next(it,"")
# iterate over the rest starting at the second char
for ch in it:
# compare prev and current
if prev in consonants and ch in vowels:
pairs.append(prev + ch)
# update prev
prev = ch
return pairs
答案 1 :(得分:3)
您可以使用正则表达式:
>>> import re
>>> def f(s):
... return re.findall(r'[bcdfghjklmnpqrstvwxyz][aeiou]',s)
...
>>> f('therapist')
['he', 'ra', 'pi']
您也可以在列表理解中使用zip
:
>>> def f(s):
... return [''.join((i,j)) for i,j in zip(s,s[1:]) if i in 'bcdfghjklmnpqrstvwxyz' and j in 'aeiou']
...
>>> s='therapist'
>>> f(s)
['he', 'ra', 'pi']
答案 2 :(得分:2)
好吧,你可以使用正则表达式。
我认为真正的问题是:“你是否构成一个元音?”
import re
def f(word):
return re.findall('[bcdfghjklmnpqrstvwxyz][aeiou]', word)
print(f("therapist")) # Prints ['he', 'ra', 'pi']
答案 3 :(得分:0)
使用re
import re
def f(word):
return re.findall(r"(?![aeiou$])\w[aeiou]",word)
>>>f('therapist')
['he', 'ra', 'pi']