【发布时间】:2021-12-17 01:18:30
【问题描述】:
我正在尝试编写一个过程来根据每个元组的产品值对列表中的元组进行排序。我只是尝试先使用 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)]
【问题讨论】:
-
为什么不使用
list.sort方法? -
例如
m.sort(key=lambda x: x[0] * x[1]) -
在python中>=3.8
import math; m.sort(key=math.prod) -
@Ch3steR 在仔细阅读您的答案后,我删除了我的评论。你写了
list.sort(m, key=...)而不是m.sort(key=...),这有点不寻常但没有错。我发表了我的评论,因为当阅读不够仔细时,我虽然您已将列表称为list并使用list.sort(key=...)对其进行排序。但这不是你在做的。所以我删除了我的评论。
标签: python sorting tuples product