如何将文件读取到列表列表? [英] How to read a file to a list of lists?

查看:78
本文介绍了如何将文件读取到列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从包含以下数据的文件中创建列表列表:

I want to create a list of lists from a file that contains the following data:

101 Rahul
102 Julie
103 Helena
104 Kally

代码

lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

我想要的输出

[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]

我得到的输出

['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']

推荐答案

您的代码:

lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

请注意两个for循环,您正在做的是循环遍历每一行,然后遍历该行中的每个项目.然后,您将每个项目分别推入列表lis. 要获得所需的输出,您需要将每行中两个项目的列表推入列表中. 实际上,您已经使用f.read().split()生成了此项目列表,因此只需要添加此项目即可. 这将为您提供以下内容:

Note the two for loops, what you are doing is looping through each line, then through each item on that line. You are then pushing each item individually into your list lis. To get the output you want, you want to be pushing a list of the two items on each line into your list. You are actually already generating this list of items with f.read().split(), so you just need to append this. This leaves you with the following:

lis = []

with open("student_details.txt" , "r+") as f:    
    for i in range(1,3,1):
        #no second loop here
        data = f.read().split()
        lis.append(data)
print(lis)

这仍然不能给我们正确的答案,这里的问题是循环, 我们可以通过意识形态地阅读每一行而无需指定任何范围来解决此问题:

This still doesn't give us the correct answer, the loop is the problem here, we can fix this by just reading each line ideomatically, without specifying any ranges:

lis = []

with open("student_details.txt" , "r+") as f:    
    for line in f:
        #no second loop here
        data = line.split()
        lis.append(data)
print(lis)

这篇关于如何将文件读取到列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆