简体   繁体   English

Python 计算列表元素的矩形面积

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

I have a list like that and I want to calculate the area of rectangle for elements of this list.我有一个这样的列表,我想计算这个列表元素的矩形面积。

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

output = 12, 30, 30, 9 output = 12, 30, 30, 9

I tried this code but output is 12,12,12,12我试过这段代码,但 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)))

That is because the usage of map() is wrong.那是因为map()的使用是错误的。 What map does is apply the function on each element of the iterable and replaces that element with the returned value. map 所做的是将 function 应用于可迭代的每个元素,并用返回的值替换该元素。

For your list, each element is a tuple of two elements so your calc() should he something like this:对于您的列表,每个元素都是两个元素的元组,因此您的calc()应该是这样的:

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

Try this way:试试这个方法:

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))

To make your life easier you can just add a list inside the function calc() and return the list and it should return [12, 30, 30, 9] .为了让您的生活更轻松,您只需在 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

Edit: As to use the map function.编辑:至于使用map function。

If you really want to do it your way then you should do it like this:如果你真的想按照自己的方式做,那么你应该这样做:

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


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


result = list(map(calc, number_list))

Since the map function provides each element of number_list then you cannot iterate over it like your solution.由于map function 提供了number_list的每个元素,因此您不能像解决方案一样对其进行迭代。 Instead just get the two elements of the tuple and multiply them.相反,只需获取元组的两个元素并将它们相乘。

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

Do not name your variable list !!* That's a reserved keyword in python.不要命名您的变量列表!!*这是 python 中的保留关键字

You can starmap the mul function to the list:您可以将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 requires to be defined correctly here. calc function 需要在这里正确定义。

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

Also list is reserved keyword in Python.还列出了 Python 中的保留关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM