gpt4 book ai didi

python - 如何在父字符串列表中查找子字符串列表对应的索引

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:50 25 4
gpt4 key购买 nike

我正在编写一个从文本文件中读取数据的代码。我使用 numpy loadtxt 加载数据它可能看起来像这样:

import numpy as np

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

我想查看我拥有的一些产品:

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

现在我想在 Shop_Products 数组中找到这些“项目”索引,而无需执行 for 循环和 if 检查。

我想知道是否可以使用任何 numpy 方法来完成:我想过使用 intercept1d查找常见项目,然后使用 searchsorted .但是,我无法对我的“产品”列表进行排序,因为我不想失去原始排序(例如,我会使用索引直接查找每个产品的库存)。

对“pythonish”解决方案有什么建议吗?

最佳答案

np.searchsorted 可以将排序排列作为可选参数:

>>> 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 中出现的顺序返回值,无论查询中的顺序如何:

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

关于python - 如何在父字符串列表中查找子字符串列表对应的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828612/

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