简体   繁体   中英

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

I tried this code but output is 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. What map does is apply the function on each element of the iterable and replaces that element with the returned value.

For your list, each element is a tuple of two elements so your calc() should he something like this:

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] .

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.

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

You can starmap the mul function to the list:

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.

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

Also list is reserved keyword in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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