簡體   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

我已經逐行閱讀了文件,但現在不知道如何將這些行變成整數列表。

這就是我所擁有的:

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 

打印(adjMatrixFromFile(“文件”))

這是文件:

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

用這個“tiny.txt”:

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

這個代碼:

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"))

我得到了這個 output:

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

假設文件看起來像這樣:

1 5 13
-7 8 99
10 0 1

使它成為一個簡單的整數列表:

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

如果無法將行的元素解析為 integer,您將收到 ValueError。

使其成為類似“列表列表”的矩陣:

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