2017-05-14 144 views
0

這是NLTK書中的一個問題,但我被卡住了。任何人都知道如何將其作爲嵌套列表理解書寫?python在nltk中嵌套列表理解

>>> words = ['attribution', 'confabulation', 'elocution', 
...   'sequoia', 'tenacious', 'unidirectional'] 
>>> vsequences = set() 
>>> for word in words: 
...  vowels = [] 
...  for char in word: 
...   if char in 'aeiou': 
...    vowels.append(char) 
...  vsequences.add(''.join(vowels)) 
>>> sorted(vsequences) 
['aiuio', 'eaiou', 'eouio', 'euoia', 'oauaio', 'uiieioa'] 

回答

3

你可以做

In [75]: ["".join([char for char in word if char in 'aeiou']) for word in words] 
Out[75]: ['aiuio', 'oauaio', 'eouio', 'euoia', 'eaiou', 'uiieioa'] 

如果你需要爲setsorted

sorted(set(["".join([char for char in word if char in 'aeiou']) for word in words])) 
+0

真棒,分享您的想法感謝! – thatMeow