将文本文件中的整数存储到数组
Storing integers from text file to an array
我的任务是将文本文件中的整数分配给 python 中的数组。
我尝试按行阅读并拆分,但 none 奏效了。
任务是这样的:我们有一个数组
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)
如果你不介意 numpy 数组和 pandas:
import pandas as pd
integers = pd.read_csv('test.txt', sep=" ", header=None)
我的任务是将文本文件中的整数分配给 python 中的数组。
我尝试按行阅读并拆分,但 none 奏效了。
任务是这样的:我们有一个数组
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)
如果你不介意 numpy 数组和 pandas:
import pandas as pd
integers = pd.read_csv('test.txt', sep=" ", header=None)