简体   繁体   English

如何在 python 中找到具有特定值的列表中所有元素的索引

[英]How to find the index for all the elements in a list with a particular value in python

I have two lists, one with the product's ID code and another with the price they were bought for.我有两张清单,一张带有产品的 ID 代码,另一张带有购买价格。

I was planning on grouping them together in a list of lists with the first element being the product ID and the following elements being the prices as seen below:我计划将它们组合在一个列表列表中,第一个元素是产品 ID,以下元素是价格,如下所示:

product_id = [40, 56, 15, 17, 12, 39, 52, 41, 14, 19, 58, 42]
price_id = [1, 9, 25, 25, 25, 1, 9, 1, 25, 25, 9, 1]
list = [[1, 40, 39, 41, 42], [9, 56, 58, 52], [25, 12, 14, 19, 17, 15]]

I would prefer to do this without pandas but I was wondering how you could do this or if it would be better to just create a data frame with pandas and sort by product ID as this would make further coding easier and the remainder has been coded assuming this layout.我宁愿在没有 pandas 的情况下执行此操作,但我想知道您如何执行此操作,或者使用 pandas 创建一个数据框并按产品 ID 排序是否会更好,因为这将使进一步编码更容易,其余部分已编码假设这种布局。

So far, I am planning on using a for loop to connect the index on the product list and price list together but I can't find all the indexes.到目前为止,我计划使用 for 循环将产品列表和价格列表上的索引连接在一起,但我找不到所有索引。 I was thinking of something like this:我在想这样的事情:

index_prod1 = [0, 5, 7, 11]
prod1 = [1]

for i in range(len(index_prod1)):
    prod1.append(price_id[i])

list = [prod1, prod9, prod25]

However, I was wondering how I could get index_prod1 , would I have to do a for loop and just append each value?但是,我想知道如何获得index_prod1 ,我是否必须做一个 for 循环,并且每个值只需 append ?

That, and how could I make it more generalised so that if there were to be more products added to both lists the model would still work as this needs to work for changing amounts of products.那,我怎样才能使它更通用,以便如果有更多产品添加到两个列表中,model 仍然可以工作,因为这需要改变产品数量。

product_id = [40, 56, 15, 17, 12, 39, 52, 41, 14, 19, 58, 42]
price_id = [1, 9, 25, 25, 25, 1, 9, 1, 25, 25, 9, 1]

out = {}
for a, b in zip(product_id, price_id):
    out.setdefault(b, []).append(a)

out = [[k, *v] for k, v in out.items()]
print(out)

Prints:印刷:

[[1, 40, 39, 41, 42], [9, 56, 52, 58], [25, 15, 17, 12, 14, 19]]

if I understand your question you could just use enumerate so you would do如果我理解你的问题,你可以使用 enumerate 所以你会这样做

for idx, i in enumerate(index_prod1):

I would be the value and idx would be the index is that what you meant我将是价值,idx 将是索引是你的意思

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM