你可以簡單地寫一個函數爲:
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