gpt4 book ai didi

python - 提高 Python 嵌套 for 循环的性能

转载 作者:行者123 更新时间:2023-11-28 22:01:05 30 4
gpt4 key购买 nike

我有两组数字,每组都在我的 Python 脚本中的一个列表中。对于第一个列表中的每个数字,我需要查看第二个列表中是否有任何数字大于它。我只需要 n2 大于 n1 的次数。 (例如,如果 numset1[7,2]numset2[6,9],我只需要 3)现在我正在这样做——遍历每个 n1 并检查每个 n2 是否大于它:

possibilities = [(n1<n2) for n1 in numset1 for n2 in numset2]
numPossibilities = sum(possibilities)

目前这是我的脚本中最慢的部分,尤其是在处理较大的数据集(包含数千个数字的 numset1 和 numset2)时。我确信有某种方法可以提高效率,但我只是不确定该怎么做。

最佳答案

numset2 进行排序,然后遍历 numset1,但对 numset2 使用二进制搜索,例如使用 bisect 模块:http://docs.python.org/2/library/bisect.html

import bisect
# your code here
numset2.sort()
L = len(numset2)
numPossibilities = sum([bisect.bisect_right(numset2,n1) < L for n1 in numset1])

另请注意,您的原始代码不会计算您在第二句话中要求的内容 - 对于 numset1 中的每个元素,它会计算 中的元素数量>numset2 都大于这个元素,而不是是否有一个元素符合条件。

要匹配您的原始代码,请执行以下操作:

numPossibilities = sum([L - bisect.bisect_right(numset2,n1) for n1 in numset1])

关于python - 提高 Python 嵌套 for 循环的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755239/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com