如果我有一个字符串列表,例如:
lst = ['aa bb', 'cc dd', 'cc aa']
我怎样才能把它变成一个独特的单词列表,例如:
['aa', 'bb', 'cc', 'dd']
使用理解?据我所知,这是无济于事的:
wordList = [x.split() for row in lst for x in row]
如果我有一个字符串列表,例如:
lst = ['aa bb', 'cc dd', 'cc aa']
我怎样才能把它变成一个独特的单词列表,例如:
['aa', 'bb', 'cc', 'dd']
使用理解?据我所知,这是无济于事的:
wordList = [x.split() for row in lst for x in row]
您想遍历拆分值:
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'])
我认为最简单的方法可能是这样,虽然不是最有效的。
set(' '.join(lst).split())
如果你真的想要一个列表,那么只需将它包装在一个调用中list()
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。
为了保持秩序,您可以执行以下操作:
>>> 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']
请注意set()
,正如 Martijn 所指出的那样,使用 a 很可能更快。