Skip to main content
 首页 » 编程设计

python之将文本文件中的整数存储到数组

2024年11月24日9Leo_wl

我的任务是将文本文件中的整数分配给 python 中的数组。

我试过按行阅读和拆分,但都没有用。

任务是这样的:我们有一个数组

1 4 5 7 3 2 8 0 0 0 0 0 0 0  
 
0 0 0 0 0 0 0 0 4 0 0 0 0 0 
 
0 0 0 0 0 0 0 0 0 3 0 0 0 0 
 
0 0 0 0 0 0 0 5 0 0 6 0 0 0 
 
0 0 0 0 0 0 0 0 0 0 1 0 0 0 
 
0 0 0 0 0 0 0 0 0 0 0 2 9 0 
 
0 0 0 0 0 0 0 0 0 0 10 0 0 0 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 11 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 1 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 8 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 9 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 14 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 5 
 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 

这需要分配给数组 x 以便在其他函数中使用它。

请您参考如下方法:

做类似的事情:

with open('my_raw_file.txt', 'r') as file: 
    all_file = file.read().strip()  # Read and remove any extra new line 
    all_file_list = all_file.split('\n')  # make a list of lines 
    final_data = [[int(each_int) for each_int in line.split()] for line in all_file_list]  # make list of list and convert to int  
    print(final_data)