Search code examples
pythonsortinglambda

How can I sort a zipped list in a certain condition?


I want to sort a zipped list, from how close it is to a certain number. Zipped Elements contain name, and a price. one name represents a price.

namesList=["Bob", "Sam", "John"]
pricesList=[10,30,40]
zipped=list(zip(namesList,pricesList))

So it currently is

[('Bob', 10), ('Sam', 30), ('John', 40)]

and I wish these numbers are sorted, where they are closest to 27.

So they should be reordered as

[('Sam', 30), ('John', 40), ('Bob', 10)]

How is that possible?

I've tried doing

sorted(list(zipped[1]), key=lambda x: abs(x-pricePerPerson))

something like this, but it would not work.


Solution

  • You are taking the [1] index too early. You should only look at that member when defining the sorting key:

    sorted(zipped, key=lambda x: abs(x[1]-pricePerPerson))