gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:51 25 4
gpt4 key购买 nike

我有两个列表,例如:

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/

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