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

Viewed 36

I have two lists, one with the product's ID code and another with the price they were bought for.

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:

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.

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. 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?

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.

2 Answers
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

for idx, i in enumerate(index_prod1):

I would be the value and idx would be the index is that what you meant

Related