Home > front end >  Is there a "function comprehension" to change a value in python
Is there a "function comprehension" to change a value in python

Time:11-04

Data is a list of lists, ig. [[1, 0], [0, 1], [1, 1]]

I have these two lines which get an average of val[0] in a list data based on if val[1] is 0

l = [val[0] for val in data if val[1] == 0]
return sum(l)/len(l)

Is there a way to calculate the sum while doing the list comprehension?

CodePudding user response:

Your question is a bit vague to me but I'm trying to give some information...

List-comprehension is supposed to create a list for you. "A syntax which creates lists". So it really depends on which value you need to exist after the iteration. Is it just the average? the result list? the sum?

If you want to have the result list and the sum while you're iterating, you can use a for loop instead:

data = [[1, 0], [0, 1], [1, 1], [4, 0]]

lst = []
total = 0
for v1, v2 in data:
    if v2 == 0:
        total  = v1
        lst.append(v1)

If you insist to do it in a list comprehension, you can do:

data = [[1, 0], [0, 1], [1, 1], [4, 0]]
total = 0

def sum_up(n):
    global total
    total  = n

lst = [sum_up(v1) or v1 for v1, v2 in data if v2 == 0]

Here the return value of the sum_up is None which is Falsy so the result list contains the value of v1 and you have total as well.

If you just intend to squeeze it in one line and have the result list and the average:

print(sum(l := [v1 for v1, v2 in data if v2 == 0]) / len(l))

Here because of walrus operator you have access to the result list l.

In the first two approaches the calculation of the sum happens while iterating through the data.

CodePudding user response:

You do not need to calculate the sum, you can directly calculate the mean (average). At least this is what your code suggests you are actually doing with dividing sum by len.

import statistics

data = [[1, 0], [0, 1], [1, 1]]
return statistics.mean((val[0] for val in data if val[1] == 0))
  • Related