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)]
再次,非常感谢任何帮助。谢谢。
解决方案
我建议你在 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/
推荐阅读
- r - 创建函数以使用带有 ggplot2 的循环
- python - 如何在 tkinter 中获取画布的尺寸?
- javascript - 试图学习 tensorflow.js,但需要一个更简单的例子,比如 Brain.js
- jquery - addClass 在 iphone Chrome 上不起作用
- java - JavaFX 中的线程和绑定
- html - Visual Studio WebBrowser 以不同于 IE 的方式呈现网页
- python - 将多个RDD行转换为pyspark中的一行
- mysql - MySQL 从多个表中的列总数中插入(复合?)行
- c - C - 程序为 SEGFAULT 提供了 for 循环,但并非没有
- c# - 如何使用 CodeDom 进行异步调用和函数定义?