简体   繁体   English

逐行读取文件并使用 split() function 使用 python 将该行分成整数列表

[英]Read the file line-by-line and use the split() function to break the line into a list of integers using python

I have read the file line by line but now do not know how to make the lines into a list of integers.我已经逐行阅读了文件,但现在不知道如何将这些行变成整数列表。

This is what I have:这就是我所拥有的:

def adjMatrixFromFile(file): def adjMatrixFromFile(文件):

Our_numbers = []
file = open(file, 'r')
n =0
while True: 
    line = file.readlines()
    if not line:
        break
    for i in line: 
        numbers = i.split(' ')
        Our_numbers.append(numbers) 
new_ourNumbers = []
for d in Our_numbers:
    for k in d:
        result = k.split(' ')
        new_ourNumbers.append(result)    
return new_ourNumbers 

print(adjMatrixFromFile("file"))打印(adjMatrixFromFile(“文件”))

this is the file:这是文件:

''''5 
    0 1 
    1 2  1 2  1 3  1 3  1 4 
    2 3 
    3 0 
    4 0  4 2 

with this "tiny.txt":用这个“tiny.txt”:

5 
0 1 
1 2  1 2  1 3  1 3  1 4 
2 3 
3 0 
4 0  4 2 

and this code:这个代码:

def adjMatrixFromFile(file):
    Our_numbers = []
    file = open(file, 'r')
    line = file.readlines()

    for i in line:
        i=i.replace('\n','') #remove all \n 
        numbers = i.split(' ')
        numbers = filter(None, numbers) #remove '' in the list
        Our_numbers.extend(numbers) #add values from a list to another list

    Our_numbers = [int(i) for i in Our_numbers] #convert all element str -> int
    return Our_numbers

print(adjMatrixFromFile("tiny.txt"))

I got this output:我得到了这个 output:

[5, 0, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 2, 3, 3, 0, 4, 0, 4, 2]

Assuming the file looks something like this:假设文件看起来像这样:

1 5 13
-7 8 99
10 0 1

Making it a simple list of integers:使它成为一个简单的整数列表:

our_numbers = []
for line in open(filename):
    our_numbers.extend( [ int(num) for num in line.split() ] )

You will get a ValueError if an element of a line cannot be parsed as integer.如果无法将行的元素解析为 integer,您将收到 ValueError。

Making it a matrix like "list of lists":使其成为类似“列表列表”的矩阵:

our_numbers = []
for line in open(filename):
    our_numbers.append( [ int(num) for num in line.split() ] )

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

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