[英]how to add together the items in a list after a certain condition is true?
我正在尝试编写一个值返回函数,其中参数是显示商店销售额和员工人数等的记录列表。
该函数遍历记录列表并计算总数
来自销售额超过 50,000 美元的商店的员工。
“records”参数是一个txt文件,包含以下格式的信息:Hm001,6,Frankton,42305.67 id, num of employees,郊区, sales count
我为收入超过 50000 的商店写了一个 if 语句。我需要帮助来显示销售额超过 50000 的商店的员工总数。
解决方案必须是通用的,并且适用于具有相同格式的任何列表。 请解释您的答案,因为我是 python 新手。
def count_employees(records):
num_of_emp = ""
for count in records:
if count[3] > 50000:
num_of_emp =
return count
编辑这是示例记录:
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
输入数据由以下记录组成:
Hm001,6,Frankton,42305.67
输入文件中每行有一条记录。 (这是 OP 重新格式化原始问题中的 inout 数据后的编辑)。
FILENAME = 'foo.txt'
VOLUME = 50_000
def emp_count(filename):
count = 0
with open(filename) as data:
for line in data:
_, emps, _, sales = line.split(',')
if float(sales) > VOLUME:
count += int(emps)
return count
print(emp_count(FILENAME))
输出:(基于问题中显示的样本数据)
101
编辑:
更改为 OP 的问题后简化的代码表明每行只有一条记录
你到底有什么问题? 不明白的地方能具体点吗? 您的问题很容易研究
您错误地初始化了 num_of_emp:
num_of_emp = "" # this should not be an empty string
您还返回了不正确的变量,因为 'count' 仅存在于 for 循环中。
好的,所以要向列表中添加新元素,您可以使用.append()
将新元素添加到列表中。
所以语法如下:
list_name.append(element)
从你给出的代码来看,我认为num_of_emp
应该是一个空列表。
num_of_emp = []
不是空字符串----> ""
所以,如果你能更具体一点,那会很有帮助。
像这样的东西应该工作。 不要测试它:
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))
def count_smth(records):
result = 0
for count in records:
if condition:
result += 1
return result
如果要返回number ,请将result
值指定为 0。您的函数返回count
,而不是结果。
您可以传入任何条件,甚至编写另一个返回布尔值的函数。
a += value
语法与 a = a + value 语法相同
两种选择:
1 - 在 Python 中,在这种情况下,您可以返回一个仅包含最佳员工的列表,如下面的代码。 然后,您可以简单地获取访问列表长度方法的这些最佳员工的数量。
def count_employees(records):
num_of_emp = []
for employee in records:
if float(employee[3]) > 50000:
num_of_emp.append(employee)
return num_of_emp
但是,您需要在调用此函数的类中创建另一个列表,以便正确获取返回的列表。 例如在 main.py
best_employees = []
records = [ <WHATEVER DATA YOU HAVE>]
best_employees = count_employees(records) #To get the list with the best employees
count_of_best_employees = best_employees.len() #To get the count of the best employees
2 - 如果您只想获取计数器,那么您可以这样做:
def count_employees(records):
counter_best_employees = 0
for employee in records:
if float(employee[3]) > 50000:
counter_best_employees = counter_best_employees + 1
return counter_best_employees
Python 是我所知道的最高级别的语言之一,并且可能有某种函数可以直接返回您想要的内容,而无需自己迭代列表,但现在就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.