除了它將接收和回傳的日志格式不同之外,我有這兩個非常相似的函式。一個看,當另一個回傳 3 時回傳 4 個值。有什么辦法可以為這 2 個創建 1 個通用函式?謝謝
> - Borrow book: B#<day>#<Student Name>#<Book name>#<days borrowed for>
> - Return book: R#<day>#<Student Name>#<Book name>
def read_borrow_log(log):
borrow_day = []
borrow_student = []
borrow_book = []
borrow_duration = []
for line in log:
hash_func = line.find("#")
hash_day = line.find("#", hash_func 1)
hash_student = line.find("#", hash_day 1)
hash_book = line.find("#", hash_student 1)
hash_duration = line.find("#", hash_book 1)
borrow_day.append(int(line[(hash_func 1):(hash_day)]))
borrow_student.append(line[(hash_day 1):(hash_student)])
borrow_book.append(line[(hash_student 1):(hash_duration)])
borrow_duration.append(line[(hash_duration 1):])
return borrow_day, borrow_student, borrow_book, borrow_duration
def read_return_log(log):
return_day = []
return_student = []
return_book = []
for line in log:
hash_func = line.find("#")
hash_day = line.find("#", hash_func 1)
hash_student = line.find("#", hash_day 1)
return_day.append(int(line[(hash_func 1):(hash_day)]))
return_student.append(line[(hash_day 1):(hash_student)])
return_book.append(line[(hash_student 1):])
return return_day, return_student, return_book
def main():
borrow_day, borrow_student, borrow_book, borrow_duration = read_borrow_log(borrow_log)
return_day, return_student, return_book = read_return_log(return_log)
uj5u.com熱心網友回復:
嘗試使用 python 的內置字串拆分:
def extract_log_parts(log):
recs = []
for line in log:
recs.append(line.split('#'))
# we want the record *columns* -- transpose the table
return tuple(map(list, zip(*recs)))
uj5u.com熱心網友回復:
您可能會做的一件事是僅在傳入某個可選引數時才完成“額外”作業,如下所示:
def read_borrow_log(log,borrow_log=True):
borrow_day = []
borrow_student = []
borrow_book = []
if borrow_log is True:
borrow_duration = []
for line in log:
hash_func = line.find("#")
hash_day = line.find("#", hash_func 1)
hash_student = line.find("#", hash_day 1)
if borrow_log is True:
hash_book = line.find("#", hash_student 1)
hash_duration = line.find("#", hash_book 1)
borrow_day.append(int(line[(hash_func 1):(hash_day)]))
borrow_student.append(line[(hash_day 1):(hash_student)])
borrow_book.append(line[(hash_student 1):(hash_duration)])
if borrow_log is True:
borrow_duration.append(line[(hash_duration 1):])
if borrow_log is True:
return borrow_day, borrow_student, borrow_book, borrow_duration
else:
return borrow_day, borrow_student, borrow_book
def main():
borrow_day, borrow_student, borrow_book, borrow_duration = read_borrow_log(borrow_log)
return_day, return_student, return_book = read_borrow_log(return_log,borrow_log=False)
但是你可能想重新考慮使用的命名約定,因為這個函式現在會做不止一件事,這對檔案目的來說是不好的(并且通常是一個不好的做法,讓函式做不止一件事,糟糕到我應該反對我的如果可以,我自己的答案)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376152.html
上一篇:排序和取消排序功能
下一篇:在R函式中輸入多個變數
