how to add together the items in a list after a certain condition is true?

Issue

I am trying to write a value return function in which the parameter is a list of records that show store sales and number of employees and such.

The function iterates through the record list and calculates the total number

of employees from stores with sales volume more than $50,000.

the "records" parameter is an txt file that contains the information
in the following format:
Hm001,6,Frankton,42305.67
id, num of employees, suburb, sales count

I have written a if statement for the stores that earn more than 50000.
I need help with showing the total number of employees from stores that have sales return of more than 50000.

the solution must be general and work for any list with the same format.
Please explain your answer as I am new to python.


def count_employees(records):
   num_of_emp = ""
   for count in records: 
      if count[3] > 50000: 
         num_of_emp = 
   return count   

EDIT this is the sample records:

Hm001,6,Frankton,42305.67
Hm002,10,Glenview,21922.22
Hm003,7,Silverdale,63277.9
Hm004,13,Glenview,83290.09
Hm005,21,Queenwood,81301.82
Hm006,14,Hillcrest,62333.3
Hm007,7,Frankton,28998.8
Hm008,19,Chartwell,51083.5
Hm009,6,Glenview,62155.72
Hm0010,8,Enderley,33075.1
Hm0011,10,Fairfield,61824.7
Hm0012,15,Rototuna,21804.8
Hm0013,11,Fairfield,62804.7

Solution

Something like this should work. Don’t tested it tho:

file = "text.txt"

def count_employees(filename):
    num_of_emp = 0
    with open(filename) as f:
        all_data = f.readlines()
        lines = all_data[0].split(" ")
        for line in lines:
            record = line.split(",")
            if float(record[3]) > 50000:
                num_of_emp += int(record[1])
    return num_of_emp

print(count_employees(file))


Answered By – laserface000

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published