numpy数组中列表的索引 [英] Index of list within a numpy array

查看:298
本文介绍了numpy数组中列表的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写一个代码,该代码使用精确的对角线化来研究Lieb-Liniger模型.第一步是构建一个numpy数组,其中包含描述粒子职业的列表.数组看起来像

So I'm writing a code that uses exact diagonalization to study the Lieb-Liniger model. The first step is building a numpy array containing lists that describe particle occupations. The array would look something like

array([[2, 0, 0],
   [1, 1, 0],
   [1, 0, 1],
   [0, 2, 0],
   [0, 1, 1],
   [0, 0, 2]])

对于2种粒子在3种模式下的情况.我的问题是,是否有可能在此数组中获取特定列表的索引,类似于您如何使用index函数在常规列表中获取索引.例如,对于列表A,我能够使用A.index(some_list_in_A)来获取该列表的索引,但是我尝试使用numpy.where(HS = [2,0,0])来获得[2,0,0]的索引(依此类推),但无济于事.对于大量的粒子和模式,我正在寻找一种获取这些索引的有效方法,并且我发现使用numpy数组非常有效,但是我只是碰到了这个问题,还没有找到解决方案.有什么建议吗?

for the case of 2 particles in 3 modes. My question is, is it possible to get the index of a particular list in this array, similar to how you would get an index in a regular list with the index function. For instance, with a list of lists, A, i was able to use A.index(some_list_in_A) to get the index of that list, but I have tried using numpy.where(HS=[2,0,0]) to get the index of [2,0,0] (and so on), but to no avail. For large numbers of particles and modes, I'm looking for an efficient way to obtain these indices, and I figured using numpy arrays were quite efficient, but I have just hit this block and have not found a solution to it. Any suggestions?

推荐答案

以下是进行此查找的几种方法:

Here are several ways of doing this lookup:

In [36]: A=np.array([[2,0,0],[1,1,0],[1,0,1],[0,2,0],[0,1,1],[0,0,2]])
In [37]: pattern = [0,2,0]

In [38]: np.where(np.all(pattern==A,1))  # Saullo's where
Out[38]: (array([3]),)

In [39]: A.tolist().index(pattern)  # your list find
Out[39]: 3

In [40]: D={tuple(a):i for i,a in enumerate(A.tolist())}  # dictionary
In [41]: D[tuple(pattern)]
Out[41]: 3

我使用元组作为字典键-元组是不可变的列表.

I am using tuples as the dictionary keys - a tuple is an immutable list.

对于这种小尺寸的字典,最快的方法是字典,特别是如果字典只能构建一次并重复使用的话.即使是动态构建,它也比np.where快.但是您应该使用更实际的尺寸对其进行测试.

For this small size, the dictionary approach is fastest, especially if the dictionary can be built once and used repeatedly. Even if constructed on the fly it is faster than the np.where. But you should test it with more realistic sizes.

Python字典的速度得到了调整,因为它们是语言操作的基础.

Python dictionaries are tuned for speed, since they are fundamental to the language's operation.

使用编译的代码,np.where中的所有内容都非常快.但是,仍然必须将A的所有元素与pattern进行比较.除了字典哈希查找之外,还有很多工作要做.

The pieces in the np.where are all fast, using compiled code. But still, it has to compare all the elements of A with the pattern. There's a lot more work than the dictionary hash lookup.

这篇关于numpy数组中列表的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆