nltk中的python嵌套列表理解

时间:2017-05-14 14:15:51

标签: python list-comprehension

这是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']

1 个答案:

答案 0 :(得分: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]))