【发布时间】:2012-11-13 05:01:47
【问题描述】:
我必须从一个 .txt 文件为购物清单构建一个函数,如下所示:
milk
cheese
bread
hotdog buns
chicken
tuna
burgers
等等。从上面的列表中,我的购物清单应该看起来像 [['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() 或整个!= '' 对每个列表都有意义吗?还是我只是没有走在正确的轨道上?
【问题讨论】:
-
我必须使用 .readline(),而不能使用 .readlines()、.read() 或 for 循环。 为什么会这样?
标签: python python-3.x