Python从列表a中查找列表b中的项目索引

标签 python algorithm performance list numpy

我有两个列表,例如:

aa=[int(1000*random.random()) for i in xrange(10000)]
bb=[int(1000*random.random()) for i in xrange(10000)]

我想要另一个列表,它告诉我列表 bb 中的项目 aa 在哪里;如果它不存在,那么我希望它返回 -1。

列表可能非常庞大,并且必须运行数千次,因此即使时间加速也会非常庞大​​。

到目前为止我能找到的最快的是:

def index_withoutexception(aa,bb):
    try:
        return aa.index(bb)
    except:
        return -1
ls = [index_withoutexception(bb,i) for i in aa]

有没有更快的方法来实现这一点?

注意if 语句的问题是我找不到返回 nan/-1 的函数,它们都抛出异常,这是缓慢的一点......我收集

最佳答案

numpy_indexed包可用于以完全矢量化的方式解决此问题(免责声明:我是其作者)。请注意,您最好也用 numpy 替换其余代码,否则势必会成为瓶颈。

import numpy_indexed as npi
i = npi.indices(aa, bb, missing='mask').filled(-1)

关于Python从列表a中查找列表b中的项目索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660876/

相关文章:

python - 如何在 django 模板中使用 for 循环将列表转换为 html <ul>

python - key 错误 : Python script executed by linux service unable to access environment var

algorithm - 对于树中节点 u-v 之间的给定路径,找到与该路径中任何节点的最大 XOR

algorithm - 亚马逊面试-设计 session 安排程序

c++ - Boost单元测试计时机制

php - json 列与多列

performance - 'svn switch' 可以比 'rm -rf && svn checkout' 慢吗?

python - logging.fileConfig() 在谷歌应用引擎上表现得很奇怪

python - 配置了多个身份验证后端,因此必须提供 `backend` 参数或为用户设置 `backend` 属性

algorithm - 寻找一种有效的算法来获得一条线