python - 使用 list(filter()) 的程序在 python 3 上运行速度极慢

标签 python python-3.x performance

我有一个处理大量数据的程序。除了几行代码有时似乎需要大约一分钟之外,大部分运行速度都非常快。

这些代码行的作用是获取 1 到 1000 个从 0 到 1000000 范围内的不同值的列表。然后,在定义的 k 次内,它们过滤该列表并删除该列表中最常出现的值(如果多个值被表示相同的次数,则只需随机一个)。

有没有一种方法可以这样写,从而减少执行时间。

我运行 Windows 10 Pro,配备 Intel I7-8086K GTX1660 和 16Gb DDR4 RAM。

k = int(new1[1])


    def most_frequent(lists):
        return max(set(lists), key=lists.count)


    ite = 0
    while ite < k:
        new = list(filter(lambda a: a != most_frequent(new), new))
        ite += 1

正如之前所说,我得到了我想要的结果,只是程序非常慢。

最佳答案

这个怎么样:

# count elements in the list

counts = {}
for x in ls:
    counts[x] = (counts.get(x) or 0) + 1

# sort counts by most frequent

counts = sorted(counts.items(), key=lambda c: -c[1])

# get top k elements

to_remove = set(c[0] for c in counts[:k])

# remove them

new_list = [x for x in ls if x not in to_remove]

关于python - 使用 list(filter()) 的程序在 python 3 上运行速度极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58256458/

相关文章:

python - Python可以在打开套接字时选择什么网络适配器吗?

python - 将字符串转换为二维 numpy 数组中的 float

python - 在输入文件中查找确切的字符串

c++ - 快速时间函数 C/C++

sql - 估算计划的绑定(bind)参数与内联值

python - 通过 BeautifulSoup 或其他基于 python 的提取器识别大量文本

Python-关于从mysql检索结果

Python - 错误 : look-behind requires fixed-width pattern

python - 在 Python 内部理解 self

android - 在 ContentValues 中查询