user2368334
user2368334

Reputation: 73

In Python, how can I search a list of elements for a value then also take the element before it?

I have a list of elements created by:

if x > 2:
            pricePerUnit.append(name)
            pricePerUnit.append(price/quantity)
bestValue = list.count(min(pricePerUnit))

How could I take the element preceding each value at the same time as I take the value?

Upvotes: 0

Views: 66

Answers (1)

Tim Heap
Tim Heap

Reputation: 1711

The best thing to do would be to structure your pricePerUnit list differently, storing both values together as a tuple:

if x > 2:
    pricePerUnit.append((name, price / quantity))

This way, when you find the best value item, you also find the name. To find the minimum value in the list, you now need to supply a key argument to min. This key function should extract the value to compare to find the minimum, which in this case is the 1st item in the tuple (name is the 0th item in the tuple):

bestValueName, bestValue = min(pricePerUnit, key=lambda ppu: ppu[1])

To find all of the items that have the best value, you should find the best value, and then find all items that have that value:

_, bestValue = min(pricePerUnit, key=lambda ppu: ppu[1])
bestValueItems = filter(lambda ppu: ppu[1] == bestValue, pricePerUnit)

Upvotes: 1

Related Questions