Python列表构建

标签 python python-3.x

我必须从 .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的使用陈述。这确保文件在不再需要后关闭。

关于Python列表构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355828/

相关文章:

python - 如何只取整数项并计算列表中的总和?

python - 装饰所有继承的方法

python - 马里奥在pygame中跑过屏幕太快

python - 更改 IPython 流编码

python - 在 Jinja2 迭代中获取倒数第二个元素

python - 为什么 lambda 函数中的括号会导致 Python 3 上的语法错误?

python - 在输出中打印的路径

c# - 将Argument数组传递给C#中的多参数函数

python - 属性错误 : 'tuple' object has no attribute 'lower'

python - 根据其他数据帧的比较创建带有列的 Pandas 数据帧