如何从句子列表中创建单词列表?

时间:2013-07-23 10:58:17

标签: python list-comprehension

如果我有一个字符串列表,例如:

lst =  ['aa bb', 'cc dd', 'cc aa']

如何将此列入一个独特单词列表,例如:

['aa', 'bb', 'cc', 'dd']

使用理解?就我而言,这是无济于事的:

wordList = [x.split() for row in lst for x in row]

4 个答案:

答案 0 :(得分:2)

您希望循环拆分值:

wordList = [word for row in lst for word in row.split()]

然后使用一个集使整个列表唯一:

wordList = list({word for row in lst for word in row.split()})

或只是使用一套并完成它:

wordList = {word for row in lst for word in row.split()}

演示:

>>> lst =  ['aa bb', 'cc dd', 'cc aa']
>>> list({word for row in lst for word in row.split()})
['aa', 'cc', 'dd', 'bb']
>>> {word for row in lst for word in row.split()}
set(['aa', 'cc', 'dd', 'bb'])

如果订单很重要(上面的代码以任意顺序返回单词,由于CPython的实现细节,排序顺序是巧合),请使用单独的集来跟踪重复值:

seen = set()
wordList = [word for row in lst for word in row.split() if word not in seen and not seen.add(word)]

为了说明差异,需要更好的输入样本:

>>> lst = ['the quick brown fox', 'brown speckled hen', 'the hen and the fox']
>>> seen = set()
>>> [word for row in lst for word in row.split() if word not in seen and not seen.add(word)]
['the', 'quick', 'brown', 'fox', 'speckled', 'hen', 'and']
>>> {word for row in lst for word in row.split()}
set(['and', 'brown', 'fox', 'speckled', 'quick', 'the', 'hen'])

答案 1 :(得分:1)

In [25]: list({y for x in lst for y in x.split()})
Out[25]: ['aa', 'cc', 'dd', 'bb']

为了保持秩序,意味着从列表中删除重复项,您可以参考http://www.peterbe.com/plog/uniqifiers-benchmark

答案 2 :(得分:1)

为了保持秩序,您可以执行以下操作:

>>> from collections import OrderedDict
>>> lst =  ['aa bb', 'cc dd', 'cc aa']
>>> new = []
>>> for i in lst:
...     new.extend(i.split())
...
>>> list(OrderedDict.fromkeys(new))
['aa', 'bb', 'cc', 'dd']

请注意,正如Martijn指出的那样,使用set()很可能更快。

答案 3 :(得分:1)

我认为最简单的方法可能就是这样,虽然不是最有效的方法。

set(' '.join(lst).split())

如果你真的想要一个列表,那么只需将其包含在list()

的调用中