我正在嘗試撰寫一個值回傳函式,其中引數是顯示商店銷售額和員工人數等的記錄串列。
該函式遍歷記錄串列并計算總數
來自銷售額超過 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
uj5u.com熱心網友回復:
輸入資料由以下記錄組成:
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 的問題后簡化的代碼表明每行只有一條記錄
uj5u.com熱心網友回復:
像這樣的東西應該作業。不要測驗它:
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))
uj5u.com熱心網友回復:
你到底有什么問題?不明白的地方能具體點嗎?您的問題很容易研究
您錯誤地初始化了 num_of_emp:
num_of_emp = "" # this should not be an empty string
您還回傳了不正確的變數,因為 'count' 僅存在于 for 回圈中。
uj5u.com熱心網友回復:
def count_smth(records):
result = 0
for count in records:
if condition:
result = 1
return result
如果要回傳number,請將result值指定為 0。您的函式回傳count,而不是結果。
如果有任何條件,您可以傳入,甚至可以撰寫另一個回傳布林值的函式。
a = value語法與 a = a 值相同
uj5u.com熱心網友回復:
好的,所以要向串列中添加一個新元素,您可以利用.append()
它向串列中添加一個新元素。
所以語法如下:
list_name.append(element)
從你給出的代碼來看,我認為num_of_emp應該是一個空串列。
num_of_emp = []
不是空字串---->""
所以,如果你能更具體一點,那會很有幫助。
uj5u.com熱心網友回復:
兩種選擇:
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 是我所知道的最高級別的語言之一,并且可能有某種函式可以直接回傳您想要的內容,而無需自己迭代串列,但現在就可以了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491761.html
