如何使用通用的 for 循环而不是列表扩展来简化这行代码?
How can I simplify this line of code using a common for loop rather than list expansion?
看看下面这段代码:
def load_data_k(fname: str, yyy_index: int, **selection):
selection_key_str = list(selection.keys())[0]
selection_value_int = selection[selection_key_str]
print(selection_value_int)
i = 0
file = open(fname)
if "top_n_lines" in selection:
lines = [next(file) for _ in range(selection_value_int)]
首先请告诉我这里为什么使用next(file)
:
lines = [next(file) for _ in range(selection_value_int)]
那么请告诉我如何使用普通的 for 循环而不是列表扩展来简化这一行。
你可以
with open(fname) as file:
lines = file.readlines()[:selection_value_int]
尽管整个文件被读入内存
这段代码:
lines = [next(file) for _ in range(selection_value_int)]
扩展为:
lines = []
for _ in range(selection_value_int):
lines.append(next(file))
然而这并没有简化任何事情。
next(file)
使用 File 对象的生成器行为
因此加载一些行而不获取整个文件
看看下面这段代码:
def load_data_k(fname: str, yyy_index: int, **selection):
selection_key_str = list(selection.keys())[0]
selection_value_int = selection[selection_key_str]
print(selection_value_int)
i = 0
file = open(fname)
if "top_n_lines" in selection:
lines = [next(file) for _ in range(selection_value_int)]
首先请告诉我这里为什么使用next(file)
:
lines = [next(file) for _ in range(selection_value_int)]
那么请告诉我如何使用普通的 for 循环而不是列表扩展来简化这一行。
你可以
with open(fname) as file:
lines = file.readlines()[:selection_value_int]
尽管整个文件被读入内存
这段代码:
lines = [next(file) for _ in range(selection_value_int)]
扩展为:
lines = []
for _ in range(selection_value_int):
lines.append(next(file))
然而这并没有简化任何事情。
next(file)
使用 File 对象的生成器行为
因此加载一些行而不获取整个文件