小编Rei*_*ier的帖子

Python:我的for循环不会遍历列表中的所有项目

在关注Python的在线课程后,我们鼓励自己编写某个程序.这不是一个标记,而只是为了练习.我不想帮助解决问题,但我需要帮助,为什么我的代码没有做我认为它会做的事情.

代码的(相关)部分如下:

raw_restaurants = file.readlines()

print(raw_restaurants)

restaurants = []
information = []
for i in raw_restaurants:
    if len(information) < 5:
        information.append(i.strip())
    if len(information) ==  5:
        restaurants.append(information)
        information = []
Run Code Online (Sandbox Code Playgroud)

这是使用的列表.原始列表是使用file.readlines()创建的列表.

['Georgie Porgie\n', '87%\n', '$$$\n', 'Canadian,Pub Food\n', '\n', 
 'Queen St. Cafe\n', '82%\n', '$\n', 'Malaysian,Thai\n', '\n', 
 'Dumplings R Us\n', '71%\n', '$\n', 'Chinese\n', '\n', 
 'Mexican Grill\n', '85%\n', '$$\n', 'Mexican\n', '\n', 
 'Deep Fried Everything\n', '52%\n', '$\n', 'Pub Food\n']
Run Code Online (Sandbox Code Playgroud)

问题是我的函数给出了输出:

[['Georgie Porgie', '87%', '$$$', 'Canadian,Pub Food', ''], 
 ['Queen St. Cafe', '82%', '$', 'Malaysian,Thai', ''], 
 ['Dumplings …
Run Code Online (Sandbox Code Playgroud)

python for-loop list python-3.x

2
推荐指数
1
解决办法
1251
查看次数

标签 统计

for-loop ×1

list ×1

python ×1

python-3.x ×1