A
A
Andrey Makarov2021-09-08 16:41:43
Python
Andrey Makarov, 2021-09-08 16:41:43

What does the highlighted code mean in iterating over a list in python?

def __init__(self, limit):
self.limit = limit
self.records = []
...
...
def get_today_stats(self):
today = dt.date.today()
return sum (rec.amount for rec in self .records
if rec.date == today)


class Record:
def __init__(self, amount, comment, date):
self.amount = float(amount)
self.comment = comment
self.date = date

cash_calculator.add_record(Record(amount =3000, comment='bar in Tannin dr', date='11/08/2019'))

Can it be written more clearly (for example, through if)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stefan, 2021-09-08
@MEDIOFF

This is a generator expression, and it is very strange that it is written in it, because sum does not accept generators, and there should be an error, there should be a list inclusion:

return sum([rec.amount for rec in self.records
if rec.date == today])

Whether it is possible to write down it more clearly (for example through if)?

It is possible, but why, you will need to create a separate list and add elements to it, why it is asked.
To learn more about such expressions , here is the source for you
.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question