简体   繁体   English

在python中将文本文件读入列表

[英]Reading a text file into list in python

I'm trying to learn python. 我正在尝试学习python。 This is a little test program that I made to read a text file into a list. 这是我将文本文件读入列表的一个小测试程序。 This is the text file: 这是文本文件:

42 1
35 5
50 2
41 6
42 3
48 4

And this is my codes: 这是我的代码:

score = [];

for i in range(0, 51):
    score.append(0);

f = open("test1.txt", "r");

for line in f:
    a, b = map(int, f.readline().split());
    score[a] = score[a] + b;

print(score);

I'm trying to imitate the array in C++ with list. 我正在尝试使用list模仿C ++中的数组。 Read in each line from the text file, first number of the line is the position in the list that will hold the value of the second number. 从文本文件中读取每一行,该行的第一个数字是列表中将保留第二个数字的值的位置。 For some reason the program is skipping the 1st, 3rd, 5th lines. 由于某种原因,程序将跳过第一,第三,第五行。 This is the result when I run the program. 这是我运行程序时的结果。

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 4, 0, 0]

It was supposed to be 应该是

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 6, 4, 0, 0, 0, 0, 0, 4, 0, 2]

Any idea where I might have done wrong? 知道我做错了什么吗? This is Python 3 这是Python 3

When you write for line in f: , that loops over the file, reading one line at a time. 当您for line in f:for line in f: ,它将循环遍历文件,一次读取一行。

Then, inside that loop, you ignore line and instead do f.readline() , which reads the next line. 然后,在该循环中,忽略命令line ,而是执行f.readline() ,以读取下一行。

So, you read line 0, ignore it, read line 1, and process it. 因此,您读取第0行,忽略它,读取第1行并进行处理。 Then read line 2, ignore it, read line 3, and process it. 然后读取第2行,忽略它,读取第3行并进行处理。 And so on. 等等。

Just use line instead of f.readline() and everything will be fine. 只需使用line而不是f.readline() ,一切都会好起来的。

The readline() call is the problem. 问题是readline()调用。 You are iterating through each line with for line in f , but each time through the loop, you read an extra line with readline() so it is only reading every other line. 您是通过与各行迭代for line in f ,而是通过每一次循环中,你看有一个额外的readline()所以只能通过阅读每隔线。

在python中,如果要使用for循环遍历每个文件,则可以使用迭代值:

a, b = map(int, line.split());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM