簡體   English   中英

使用元組的列表理解

[英]List comprehension with tuples

list_of_tuples = [(2, 4), (3, 3), (4, 2)]

def my_function(list_of_tuples):
  best = list_of_tuples[0]
    for r in list_of_tuples:
        if r[0] * r[1] > best[0] * best[1]:
            best = r
    return best

我想把上面的 function 寫成一行,這是我的結果

return [i for i in rectangles if i[0] * i[1] > list_of_tuples[0][0] * list_of_tuples[0][1]]

問題是我不知道如何用best = r來寫那部分。 我怎樣才能做到這一點?

Python 可以幫助您:

def my_function(list_of_tuples):
    return max(list_of_tuples, key=lambda k: k[0]*k[1])

您可以使用operator.mul()functools.reduce()獲取每個元組中每個元素的乘積,然后您可以使用max()獲取具有最大乘積的元組。

Tim Roberts 的答案適用於只有大小為 2 的元組的情況,但這種方法可用於任意長度的元組(每個元組中的元素數量甚至不必相同:):

from operator import mul
from functools import reduce

max(list_of_tuples, key=lambda x: reduce(mul, x))

更簡單的,你可以這樣做:

from math import prod

max(list_of_tuples, key=prod)

根據Kelly Bundy的建議。

這些 output:

(3, 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM