加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何加快列表理解

发布时间:2020-12-20 12:40:49 所属栏目:Python 来源:网络整理
导读:以下是我的清单: col = [['red','yellow','blue','red','green','yellow'],['pink','orange','brown','pink','brown'] ] 我的目标是消除每个列表中出现一次的项目. 这是我的代码: eliminate = [[w for w in c if c.count(w)1]for c in col]Output: [['red'
以下是我的清单:

col = [['red','yellow','blue','red','green','yellow'],['pink','orange','brown','pink','brown']
      ]

我的目标是消除每个列表中出现一次的项目.

这是我的代码:

eliminate = [[w for w in c if c.count(w)>1]for c in col]

Output: [['red','brown']]

该代码适用于小数据集,例如上面的列表,但是,我的数据集非常大.每个列表最多包含1000个项目.

有没有办法让上面的代码更快?比如将代码分解为两个或更多个for循环,因为我的理解是正常的for循环比列表理解更快.

有什么建议?谢谢.

解决方法

我想尝试一下OrderedCounter来避免重复的.count()调用:

from collections import OrderedDict,Counter

col=[['red','brown']]

class OrderedCounter(Counter,OrderedDict):
    pass

new = [[k for k,v in OrderedCounter(el).iteritems() if v != 1] for el in col]
# [['red','brown']]

如果我们只是希望迭代一次,那么(类似于Martijn的 – 加上少用套装):

from itertools import count
def unique_plurals(iterable):
    seen = {}
    return [el for el in iterable if next(seen.setdefault(el,count())) == 1]

new = map(unique_plurals,col)

这在指定需要多少次出现方面更灵活,并且保留一个dict而不是多个set.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读