Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python列表理解:列出不重复的子项_Python - Fatal编程技术网

Python列表理解:列出不重复的子项

Python列表理解:列出不重复的子项,python,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'] 如何修改列表理解以删除重复项?您可以

我正在尝试打印列表中所有单词中的所有字母,没有重复

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


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

您可以使用
set
删除重复项,但不保留顺序

>>> letterlist = list({x for y in wordlist for x in y})
>>> letterlist
['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't']
>>> 

如果要编辑自己的代码:

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

其他:


你关心维持秩序吗

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

虽然所有其他答案不能维持秩序,但此代码可以:

from collections import OrderedDict
letterlist = list(OrderedDict.fromkeys(letterlist))
另请参阅一篇关于基准测试的几种方法的文章:。

两种方法:

维持秩序:

>>> 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]

建立一个非字母列表的列表纯粹是为了改变字母列表,所以你只想使用列表理解吗?你可以做
[字母列表。如果x不在字母列表中,在单词列表中为y添加x]
这可以写成
set().union(*wordlist)
允许
set
处理多个iterables,并且不需要先将它们连接到字符串。这个答案似乎不起作用:
>>wordlist=list(OrderedDict.fromkeys(wordlist))>>>wordlist['cat','dog','rabbit']
请注意,我的代码使用的是“字母列表”,而不是您的代码使用的“单词列表”。这很有意义。感谢您的解释:-)
>>> 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]