我有一百万个数字:N[],还有一个单一的数字n,现在我想在这一百万个数字中找出与那个数字相似的数字,比如说n-10的面积,n+10。在python中,最好的方法是什么?我是否必须对1M数字进行排序并进行迭代?
发布于 2010-04-02 11:50:12
[x for x in N if n - 10 <= x <= n + 10]
发布于 2010-04-02 11:51:09
results=[x for x in numbers if x >= n-10 and x <= n+10]发布于 2010-04-02 11:56:31
另一种解决方案:
is_close_to_n = lambda x: n-10 <= x <= n+10
result = filter(is_close_to_n, N)概括一下:
def is_close_to(n):
f = lambda x: n-10 <= x <= n+10
return f
result12 = filter(is_close_to(12), N)
result123 = filter(is_close_to(123), N)不要排序。排序一般是O( n);暴力搜索是O(n )。
https://stackoverflow.com/questions/2564896
复制相似问题