我应该扩展代码使其更易于阅读,还是保持原样?

2024-04-19 14:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)]

再次感谢您的帮助。谢谢。你知道吗


Tags: 代码intxt编辑forreadconfwith
1条回答
网友
1楼 · 发布于 2024-04-19 14:21:34

我建议您在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/

相关问题 更多 >