簡體   English   中英

Python 計算列表元素的矩形面積

[英]Python calculating area of rectangle for elements of a list

我有一個這樣的列表,我想計算這個列表元素的矩形面積。

list = [(3,4),(10,3),(5,6),(1,9)]

output = 12, 30, 30, 9

我試過這段代碼,但 output 是12,12,12,12

list = [(3,4),(10,3),(5,6),(1,9)]

def calc(x,):
    for i,j in list:
        return i*j


print(list(map(calc, list)))

那是因為map()的使用是錯誤的。 map 所做的是將 function 應用於可迭代的每個元素,並用返回的值替換該元素。

對於您的列表,每個元素都是兩個元素的元組,因此您的calc()應該是這樣的:

def calc(x):
    return x[0] * x[1]

試試這個方法:

def calc(lst):
    final = []
    for i,j in lst.items():
        final.append(i * j)
    return final
your_list = [(3,4),(10,3),(5,6),(1,9)]
print(calc(your_list))

為了讓您的生活更輕松,您只需在 function calc()中添加一個列表並返回該列表,它應該返回[12, 30, 30, 9]

number_list = [(3, 4), (10, 3), (5, 6), (1, 9)]


def calc(x):
    result = []

    for i, j in x:
        result.append(i*j)

    return result

編輯:至於使用map function。

如果你真的想按照自己的方式做,那么你應該這樣做:

number_list = [(3, 4), (10, 3), (5, 6), (1, 9)]


def calc(x):
    return x[0] * x[1]


result = list(map(calc, number_list))

由於map function 提供了number_list的每個元素,因此您不能像解決方案一樣對其進行迭代。 相反,只需獲取元組的兩個元素並將它們相乘。

list_of_tuples = [(3,4),(10,3),(5,6),(1,9)]
res = list(map(lambda _tup: _tup[0] * _tup[1], list_of_tuples))

不要命名您的變量列表!!*這是 python 中的保留關鍵字

您可以將mul starmap星圖映射到列表:

from itertools import starmap
from operator import mul

lst = [(3,4),(10,3),(5,6),(1,9)]

list(starmap(mul, lst))
# [12, 30, 30, 9]

calc function 需要在這里正確定義。

def calc(x): 返回 x[0]*x[1]

還列出了 Python 中的保留關鍵字。

暫無
暫無

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

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