Im trying to write a procedure to sort the tuples in a list based on their product value per tuple. I just tried sorting them first using a while loop but Im not able to integrate the multiplication of the numbers inside the tuple. The code I have so far is:
def sort_list (a):
i = 0
while i < len(a):
key = i
j = i 1
#first checking throuh the whole list if any number is bigger
while j < len(a):
if a[key] > a [j]:
key = j
j = 1
#swap the numbers if the key one (i) is bigger than the j one the j one will be the new key
# and swapped in the next section!
a[i], a[key] = a[key], a[i]
i = 1
return a
m = [(2, 3.0), (3, 1.0), (4, 2.5), (1, 1.0)]
sort_list(m)
print (m)
# should output : [(1, 1.0), (3, 1.0), (2, 3.0), (4, 2.5)]
CodePudding user response:
The list class has a method .sort which sorts in-place and has a key argument to specify custom comparison.
list.sort:keyspecifies a function of one argument that is used to extract a comparison key from each list element (for example,key=str.lower). Thekeycorresponding to each item in the list is calculated once and then used for the entire sorting process. The default value ofNonemeans that list items are sorted directly without calculating a separate key value.
Python>=3.8
In your case, we need to calculate the product of all the elements in the tuple. We can use math.prod1 similar to sum.
from math import prod
m = [(2, 3.0), (3, 1.0), (4, 2.5), (1, 1.0)]
m.sort(key=prod)
# list -> [(1, 1.0), (3, 1.0), (2, 3.0), (4, 2.5)]
I used math.prod to generalize the solution giving you the flexibility to use the solution on arbitrary length iterable.
Python < 3.8
We can use functools.reduce with operator.mul to generalize to make it work with arbitrary length iterable.
from functools import reduce, partial
from operator import mul
prod = partial(reduce, mul)
m.sort(key=prod)
1. math.prod is available from python3.8
CodePudding user response:
Use list.sort() or sorted() with key argument
Since Python 3.8 there is a function math.prod which can calculate the product of items in a tuple. You can use it as the key argument like that:
import math.prod
m = [(2, 3.0), (3, 1.0), (4, 2.5), (1, 1.0)]
list.sort(m, key=math.prod)
print(m)
Prior to Python 3.8 you can accomplish that with lambda (or any other function):
m = [(2, 3.0), (3, 1.0), (4, 2.5), (1, 1.0)]
list.sort(m, key=lambda x: x[0] * x[1])
print(m)
The difference between list.sort() and sorted() is that list.sort() is changing m in place so you don't have to assign it to m again. If you use sorted() on the other hand, the sorted list is beeing returned as a new list so you would have to assign it t m.
CodePudding user response:
list.sort and sorted both let you specify a key argument, which should be a function giving a "score" which will be used for sorting. In your case, we just have to make this score the product of the tuple elements:
sorted(m, key=lambda x: x[0]*x[1])
