代码之家  ›  专栏  ›  技术社区  ›  user366312

如何使用公共for循环而不是列表扩展来简化这行代码?

  •  -1
  • user366312  · 技术社区  · 4 年前

    看看下面的代码:

    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循环而不是列表扩展来简化这一行。

    2 回复  |  直到 4 年前
        1
  •  1
  •   Michał Darowny    4 年前

    这个片段:

    lines = [next(file) for _ in range(selection_value_int)]
    

    扩展到:

    lines = []
    for _ in range(selection_value_int):
        lines.append(next(file))
    

    然而,这并不能简化任何事情。

    next(file) 使用文件对象的生成器行为 因此,在不获取整个文件的情况下加载一些行

        2
  •  0
  •   Andrew Ryan    4 年前

    你可以

    with open(fname) as file:
        lines = file.readlines()[:selection_value_int]
    

    尽管整个文件都被读入了内存