首页 > 解决方案 > 我应该扩展我的代码使其更易于阅读,还是保持原样?

问题描述

我在 GCSE 学习计算机科学。我可以相当自信地编码,我只是无法让我的代码更有效率。

例如,这条线路music = [[a,s] for a,s in (x.split(':') for x in open("conf/music.txt").read().split("\n"))]对我来说似乎很有效率,但显然我对其他人有不同的想法。

我想我要问的是:即使因此创建了更多变量,扩展我的代码使其更易于阅读通常会更好吗?

任何帮助将不胜感激,谢谢:)

编辑:这是(下面)更好的解决方案吗?

with open("conf/music.txt") as f: fr = f.read() e = fr.split("\n") fl = [[a,s] for a,s in (x.split(":") for x in e)]

再次,非常感谢任何帮助。谢谢。

标签: pythonpython-3.xcode-formattingmemory-efficient

解决方案


我建议你在 python 中使用 WITH 子句,它更 Python 且易于阅读。

with open("welcome.txt") as file: # Use file to refer to the file object
    file.readline()
    #do something with data

https://preshing.com/20110920/the-python-with-statement-by-example/ https://preshing.com/20110920/the-python-with-statement-by-example/


推荐阅读