Skip to main content
 首页 » 编程设计

Python列表构建

2025年05月04日12zengkefu

我必须从 .txt 文件构建一个购物 list 函数,如下所示:

milk 
cheese 
 
bread 
hotdog buns 
 
chicken 
tuna 
burgers 

等等。从上面的列表中,我的购物 list 应该看起来像 [['milk', 'cheese'], ['bread', 'hotdog buns'], ['chicken', 'tuna', 'burgers']] ,所以一个列表的列表,当文本文件中的项目之间有空格时,这些列表中的项目被分开。

我必须使用 .readline(),而我不能使用 .readlines()、.read() 或 for循环。我的代码现在创建一个空列表:

def grocery_list(foods): 
    L = open(foods, 'r') 
    food = [] 
    sublist = [] 
    while L.readline() != '': 
        if L.readline() != '\n': 
            sublist.append(L.readline().rstrip('\n')) 
        elif L.readline() == '\n': 
            food.append(sublist) 
            sublist = [] 
    return food 

我不知道哪里出了问题,所以它返回一个完全空的列表。我也不确定 '' 和 '\n' 部分;我正在使用的示例测试文件在 shell 中打开时如下所示:

milk\n 
cheese\n 
\n 
... 
'' 
'' 

但是 .rstrip() 或整个 != '' 是否对每个列表都有意义?或者我只是没有走在正确的轨道上?

请您参考如下方法:

一个问题是您没有添加最终的 sublist结果。正如@Xymostech 提到的,您需要捕获每次调用 readline() 的结果。因为下一个电话会有所不同。以下是我将如何修改您的代码。

def grocery_list(foods): 
    with open(foods, 'r') as L:         
        food = []             
        sublist = []             
 
        while True: 
            line = L.readline() 
            if len(line) == 0: 
                break 
 
            #remove the trailing \n or \r 
            line = line.rstrip() 
 
            if len(line) == 0: 
                food.append(sublist) 
                sublist = []                     
            else: 
                sublist.append(line) 
        if len(sublist) > 0: 
            food.append(sublist) 
 
        return food 

注意with的使用陈述。这确保文件在不再需要后关闭。