2013-07-21 24 views
2

我试图列出列表中所有单词的所有字母,没有重复。Python列表理解:列出没有重复项的子项

wordlist = ['cat','dog','rabbit'] 
letterlist = [] 
[[letterlist.append(x) for x in y] for y in wordlist] 

上面的代码生成['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't'],而我要找['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

如何修改列表理解来删除重复项?

+0

所以你只想使用列表理解? – rnbcoder

+1

如果x不在字串列表中,你可以在''wordlist.append(x)for y in wordlist for x in y'' – karthikr

回答

2

如果你想编辑你自己的代码:

[[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist] 

list(set([[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist])) 

其他:

list(set(''.join(wordlist))) 
0

您可以使用set删除重复项,但订单不被保留。

>>> letterlist = list({x for y in wordlist for x in y}) 
>>> letterlist 
['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't'] 
>>> 
0
wordlist = ['cat','dog','rabbit'] 
s = set() 
[[s.add(x) for x in y] for y in wordlist] 
10

你在乎关于维持秩序?

>>> wordlist = ['cat','dog','rabbit'] 
>>> set(''.join(wordlist)) 
{'o', 'i', 'g', 'd', 'c', 'b', 'a', 't', 'r'} 
+4

这可以写成'set()。union(* wordlist)'''set'请注意多次迭代,并且不要求首先将它们连接到一个字符串 –

3

而所有其他的答案不维持秩序,这个代码:

from collections import OrderedDict 
letterlist = list(OrderedDict.fromkeys(letterlist)) 

也看到的,文章对几种方法与基准:Fastest way to uniqify a list in Python

+0

这个答案似乎不起作用:>>> >>> wordlist = list(OrderedDict.fromkeys(wordlist)) >>> wordlist [猫','狗','兔']' – Mingyu

+0

请注意,我的代码使用'字母列表'而不是您的代码使用的'wordlist'。 –

+0

然后这是有道理的。感谢您的解释:-) – Mingyu

4

两种方法:

维持秩序:

>>> from itertools import chain 
>>> from collections import OrderedDict 
>>> list(OrderedDict.fromkeys(chain.from_iterable(wordlist))) 
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] 

如果你不大惊小怪顺序:

>>> list(set().union(*wordlist)) 
['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't'] 

无论这种使用列表谱曲的副作用,如:

[[letterlist.append(x) for x in y] for y in wordlist] 

正在建立一个清单Nones纯粹是为了改变letterlist