如何在父字符串列表发现,对应于一个子字符串列表的索引 [英] How to find in a parent string list, the indexes corresponding to a child string list

查看:76
本文介绍了如何在父字符串列表发现,对应于一个子字符串列表的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个code从一个文本文件中读取数据。我使用加载数据numpy的<一个href=\"https://www.google.es/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAA&url=http%3A%2F%2Fdocs.scipy.org%2Fdoc%2Fnumpy%2Freference%2Fgenerated%2Fnumpy.loadtxt.html&ei=1RU5VdHQAYuO7AbjuIH4DQ&usg=AFQjCNHn0nfFa-hFfHa_82Fnz4PssUIVlw&sig2=ED4HgmHzzF1PcmdwiCtmqg&bvm=bv.91427555,d.ZWU\"相对=nofollow> loadtxt ,它可能看起来像这样的:

I am writing a code which reads data from a text file. I load the data using numpy loadtxt and it could look like something like this:

import numpy as np

Shop_Products  = np.array(['Tomatos', 'Bread' , 'Tuna', 'Milk', 'Cheese'])
Shop_Inventory = np.array([12, 6, 10, 7, 8])

我要检查一些我的产品:

I want to check some of the products I have:

Shop_Query     = np.array(['Cheese', 'Bread']

现在我想找到Shop_Products数组中的这些项目的indeces没有做一个for循环,如果检查。

Now I would like to find these "items" indeces in the Shop_Products array without doing a for loop and if checks.

我不知道它是否能与任何numpy的方法进行:我想使用的 intercept1d 以找到共同的项目,然后用的 searchsorted 。但是,因为我不希望丢失原来的排序(例如我会使用索引来直视每种产品的库存)我无法排序我的产品列表中。

I wondered if it could be done with any of the numpy methods: I thought of using a intercept1d to find the common items and then use searchsorted. However, I cannot sort my "Products" list since I do not want to loose the original sorting (for example I would use the indexes to directly look for the inventory of each product).

在pythonish的解决方案有什么建议?

Any advice on the "pythonish" solution?

推荐答案

np.searchsorted 可以采取分类排列作为可选参数:

np.searchsorted can take a sorting permutation as an optional argument:

>>> sorter = np.argsort(Shop_Products)
>>> sorter[np.searchsorted(Shop_Products, Shop_Query, sorter=sorter)]
array([4, 1])
>>> Shop_Inventory[sorter[np.searchsorted(Shop_Products, Shop_Query, sorter=sorter)]]
array([8, 6])

这是可能比 np.in1d​​ ,这也需要对数组进行排序更快。它还返回值以相同的顺序,因为他们拿出在 Shop_Query ,而 np.1d 将返回值他们拿出在 Shop_Products 的顺序,无论在查询排序的:

This is probably faster than np.in1d, which also needs to sort the array. It also returns values in the same order as they come up in Shop_Query, while np.1d will return the values in the order they come up in Shop_Products, regardless of the ordering in the query:

>>> np.in1d(Shop_Products, ['Cheese', 'Bread']).nonzero()
(array([1, 4]),)
>>> np.in1d(Shop_Products, ['Bread', 'Cheese']).nonzero()
(array([1, 4]),)

这篇关于如何在父字符串列表发现,对应于一个子字符串列表的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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