繁体   English   中英

Python list comprehension:列出没有重复项的子项

[英]Python list comprehension: list sub-items without duplicates

我试图打印列表中所有单词中的所有字母,没有重复。

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']
>>> set(''.join(wordlist))
{'o', 'i', 'g', 'd', 'c', 'b', 'a', 't', 'r'}

两种方法:

保留订单:

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

这两种方法都没有使用list-comps来实现副作用,例如:

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

正在构建Nones列表纯粹是为了改变letterlist

虽然所有其他答案都不维护顺序,但此代码可以:

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

另请参阅一篇关于基准测试的几种方法的文章: 在Python中统一列表的最快方法

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

[[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)))

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM