-
@ChatGPT cpp 最小费用最大流算法
-
@ChatGPT cpp 最小费用最大流算法
-
以下代码怎么优化?
def doit(self): fileName='last_pid' ofile = open(fileName, "r") last_pid = ofile.read() _last_pid = self.get_unread(last_pid=int(last_pid)) print ("最新PID: ", _last_pid) if _last_pid > int(last_pid): with open(fileName,'w',encoding='utf-8') as file: file.write(str(_last_pid)) time.sleep(5) self.doit() -
以下代码怎么优化?
def doit(self): fileName='last_pid' ofile = open(fileName, "r") last_pid = ofile.read() _last_pid = self.get_unread(last_pid=int(last_pid)) print ("最新PID: ", _last_pid) if _last_pid > int(last_pid): with open(fileName,'w',encoding='utf-8') as file: file.write(str(_last_pid)) time.sleep(5) self.doit()可以优化为:
def doit(self): fileName='last_pid' with open(fileName, "r") as ofile: last_pid = int(ofile.read()) _last_pid = self.get_unread(last_pid=last_pid) print ("最新PID: ", _last_pid) if _last_pid > last_pid: with open(fileName,'w',encoding='utf-8') as file: file.write(str(_last_pid)) time.sleep(5) self.doit()优化内容:
- 使用with语句,可以自动关闭文件,不用每次手动关闭文件。
- 将ofile.read()从字符串转换为整型,减少后面的数据类型转换。
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login