在 Python 中根据元组的乘积对列表中的元组进行排序

Jan*_*s02 3 python sorting product tuples

我正在尝试编写一个过程来根据每个元组的乘积值对列表中的元组进行排序。我只是尝试先使用 while 循环对它们进行排序,但我无法整合元组内数字的乘法。到目前为止我的代码是:

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)]
Run Code Online (Sandbox Code Playgroud)

Ch3*_*teR 5

该类list有一个.sort就地排序的方法,并有一个key参数来指定自定义比较。

  • list.sort:

    key指定一个只有一个参数的函数,用于从每个列表元素中提取比较键(例如,key=str.lower)。key列表中每一项的对应值都会计算一次,然后用于整个排序过程。默认值None表示列表项直接排序,而不计算单独的键值。

Python >= 3.8

在您的情况下,我们需要计算元组中所有元素的乘积。我们可以使用math.prod1类似于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)]
Run Code Online (Sandbox Code Playgroud)

Online Demo

我曾经math.prod概括该解决方案,使您可以灵活地在任意长度的可迭代上使用该解决方案。

Python < 3.8

我们可以使用functools.reducewithoperator.mul进行泛化,使其适用于任意长度的可迭代。下面的代码也适用于Python2.7。

from functools import reduce, partial
from operator import mul

prod = partial(reduce, mul)
m.sort(key=prod)
Run Code Online (Sandbox Code Playgroud)

Online Demo


1.从python3.8math.prod开始可用