4

我目前正在开发一个高性能 python 2.7 项目,该项目使用大小为一万个元素的列表。显然,每个操作都必须尽可能快地执行。

所以,我有两个列表:一个是唯一任意数字的列表,我们称它为 A,另一个是线性列表,从 1 开始,长度与第一个列表相同,命名为 B,表示索引在 A 中(从 1 开始)

类似枚举的东西,从 1 开始。

例如:

A = [500, 300, 400, 200, 100] # The order here is arbitrary, they can be any integers, but every integer can only exist once
B = [  1,   2,   3,   4,   5] # This is fixed, starting from 1, with exactly as many elements as A

如果我有 B 的一个元素(称为 e_B)并想要 A 中的相应元素,我可以简单地做correspond_e_A = A[e_B - 1]. 没问题。

但是现在我有一个巨大的随机、非唯一整数列表,我想知道 A 中的整数的索引,以及 B 中的相应元素是什么。

我想我对第一个问题有一个合理的解决方案:

indices_of_existing = numpy.nonzero(numpy.in1d(random_list, A))[0]

这种方法的优点是不需要 map() 单个操作,numpy 的 in1d 只返回一个类似 [True, True, False, True, ...] 的列表。使用 nonzero() 我可以获得 A 中存在的 random_list 中元素的索引。我认为完美。

但是对于第二个问题,我很困惑。我试过类似的东西:

corresponding_e_B = map(lambda x: numpy.where(A==x)[0][0] + 1, random_list))

这正确地给了我索引,但它不是最优的,因为首先我需要一个 map(),其次我需要一个 lambda,最后 numpy.where() 在找到项目后不会停止(记住,A 只有唯一元素),这意味着它可以与像我这样的巨大数据集进行可怕的扩展。

我看了一下 bisect,但似乎 bisect 仅适用于单个请求,而不适用于列表,这意味着我仍然必须使用 map() 并按元素构建我的列表(这很慢,不是吗?)

由于我对 Python 很陌生,我希望这里的任何人都可能有一个想法?也许我还不知道的图书馆?

4

2 回答 2

4

我认为您最好使用哈希表进行查找numpy.in1d,而不是使用O(n log n)合并排序作为预处理步骤。

>>> A = [500, 300, 400, 200, 100]
>>> index = { k:i for i,k in enumerate(A, 1) }
>>> random_list = [200, 100, 50]
>>> [i for i,x in enumerate(random_list) if x in index]
[0, 1]
>>> map(index.get, random_list)
[4, 5, None]
>>> filter(None, map(index.get, random_list))
[4, 5]

这是 Python 2,在 Python 3 中mapfilter返回类似生成器的对象,因此list如果您想将结果作为列表获取,则需要一个环绕过滤器。

我尝试尽可能多地使用内置函数将计算负担推到 C 端(假设您使用 CPython)。所有名称都是预先解析的,所以应该很快。

一般来说,为了获得最佳性能,您可能需要考虑使用PyPy,这是一个带有 JIT 编译的绝佳替代 Python 实现。

比较多种方法的基准绝不是一个坏主意:

import sys
is_pypy = '__pypy__' in sys.builtin_module_names

import timeit
import random
if not is_pypy:
  import numpy
import bisect

n = 10000
m = 10000
q = 100

A = set()
while len(A) < n: A.add(random.randint(0,2*n))
A = list(A)

queries = set()
while len(queries) < m: queries.add(random.randint(0,2*n))
queries = list(queries)

# these two solve question one (find indices of queries that exist in A)
if not is_pypy:
  def fun11():
    for _ in range(q):
      numpy.nonzero(numpy.in1d(queries, A))[0]

def fun12():
  index = set(A)
  for _ in range(q):
    [i for i,x in enumerate(queries) if x in index]

# these three solve question two (find according entries of B)
def fun21():
  index = { k:i for i,k in enumerate(A, 1) }
  for _ in range(q):
    [index[i] for i in queries if i in index]

def fun22():
  index = { k:i for i,k in enumerate(A, 1) }
  for _ in range(q):
    list(filter(None, map(index.get, queries)))

def findit(keys, values, key):
  i = bisect.bisect(keys, key)
  if i == len(keys) or keys[i] != key:
    return None
  return values[i]

def fun23():
  keys, values = zip(*sorted((k,i) for i,k in enumerate(A,1)))
  for _ in range(q):
    list(filter(None, [findit(keys, values, x) for x in queries]))

if not is_pypy:
  # note this does not filter out nonexisting elements
  def fun24():
    I = numpy.argsort(A)
    ss = numpy.searchsorted
    maxi = len(I)
    for _ in range(q):   
      a = ss(A, queries, sorter=I)
      I[a[a<maxi]]

tests = ("fun12", "fun21", "fun22", "fun23")
if not is_pypy: tests = ("fun11",) + tests + ("fun24",)

if is_pypy:
  # warmup
  for f in tests:
    timeit.timeit("%s()" % f, setup = "from __main__ import %s" % f, number=20)

# actual timing
for f in tests:
  print("%s: %.3f" % (f, timeit.timeit("%s()" % f, setup = "from __main__ import %s" % f, number=3)))

结果:

$ python2 -V
Python 2.7.6
$ python3 -V
Python 3.3.3
$ pypy -V
Python 2.7.3 (87aa9de10f9ca71da9ab4a3d53e0ba176b67d086, Dec 04 2013, 12:50:47)
[PyPy 2.2.1 with GCC 4.8.2]
$ python2 test.py
fun11: 1.016
fun12: 0.349
fun21: 0.302
fun22: 0.276
fun23: 2.432
fun24: 0.897
$ python3 test.py
fun11: 0.973
fun12: 0.382
fun21: 0.423
fun22: 0.341
fun23: 3.650
fun24: 0.894
$ pypy ~/tmp/test.py
fun12: 0.087
fun21: 0.073
fun22: 0.128
fun23: 1.131

您可以根据您的场景调整n(size of A)、m(size of random_list) 和q(number of queries)。令我惊讶的是,我尝试变得聪明并使用内置函数而不是列表组合并没有得到回报,因为fun22它并没有比fun21(在 Python 2 中只有 ~10% 和在 Python 3 中 ~25%,但几乎慢 75%在 PyPy 中)。这里是一个过早优化的案例。我猜这个差异是由于fun22在 Python 2 中每个查询都建立了一个不必要的临时列表。我们还看到二进制搜索非常糟糕(看fun23)。

于 2014-02-01T19:49:19.617 回答
2
def numpy_optimized(index, values):
    I = np.argsort(values)
    Q = np.searchsorted(values, index, sorter=I)
    return I[Q]

这计算与 OP 相同的东西,但索引的顺序与查询的值匹配,我想这是对功能的改进。它比我机器上的 OP 解决方案快两倍;如果我正确解释了您的基准,它会稍微领先于非 pypy 解决方案。

或者如果我们不能假设所有索引都存在于值中,并且希望丢失的查询被静默删除:

def numpy_optimized_filtered(index, values):
    I = np.argsort(values)
    Q = np.searchsorted(values, index, sorter=I)
    Z = I[Q]
    return Z[values[Z]==index]
于 2014-02-01T23:04:07.983 回答