你可以简单地写一个函数为:
def func(astr):
vowels = set('aeiouAEIOU')
# Container for all unique not-vowels after the last vowel
unique_notvowels = set()
# iterate over reversed string that way you don't need to reset the index
# every time a vowel is encountered.
for idx, item in enumerate(astr[::-1], 1):
if item in vowels:
# return the vowel, the index of the vowel and the container
return astr[-idx], len(astr)-idx, unique_notvowels
unique_notvowels.add(item)
# In case no vowel is found this will raise an Exception. You might want/need
# a different behavior...
raise ValueError('no vowels found')
例如:
>>> func('asjhdskfdsbfkdes')
('e', 14, {'s'})
>>> func('asjhdskfdsbfkds')
('a', 0, {'b', 'd', 'f', 'h', 'j', 'k', 's'})
它返回最后的元音,元音a的索引在最后一个元音之后找出所有独特的非元音。
如果应该订购元音,您需要使用有序容器而不是集合,例如list
(可能要慢得多)或collections.OrderedDict
(内存更贵,但比列表更快)。
为什么将_adding_'i'放到'last_vowel_index'上? – khelwood
你是在讨论if循环还是打印时?或者地狱,甚至两个? – manoman181
'last_vowel_index + = i' < - 这。我想不出任何理由。 – khelwood