我有一个处理大量数据的程序。除了几行代码有时似乎需要大约一分钟之外,大部分运行速度都非常快。
这些代码行的作用是获取 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/