Home > Mobile >  How to use for loop inside map python
How to use for loop inside map python

Time:06-22

I have a function that returns a list of numbers. But I know in other languages like JS we don't need to set a variable like c = 0. I see about map in python but I don't know how can I do it Here is my function:

def get_bought_passenger_count(self):
    c = 0
    for book in self.bookings.all():
        c  = book.passenger_count
    return c

I want to do this with map function

CodePudding user response:

I don't think it's neccessary.

you are just constantly adding terms, so it's just a sum and it doesn't require to use the map() function, you could use the builtin sum() function, and a generator:

def get_bought_passengers(self):
    return sum(book.passenger_count for book in self.bookings.all())

as @Lecdi said in the comments.

CodePudding user response:

You can use sum together with list comprehension

def get_bought_passengers(self):
    return sum([book.passenger_count for book in self.bookings.all()])

CodePudding user response:

if you want to get the count of objects in queryset You can use count() Function...

MyModel.objects.all().count() # return the Number of Objects in the Queryset 
# count is faster than sum 
  • Related