Python:从fi读取各种数据类型

2024-09-19 19:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从matlab切换到python。 我想导入的数据是这样的

4
6
2
1
2.0E8
0.2
0.002

1 2 6
2 3 4
2 4 5
2 5 6

0 0
1 0
2 0
2 1
1 1
0 1

4 0 -150

1 1 1
6 1 1

这就是我在matlab中读到的

^{pr2}$

如何在python中导入这些数据?我没有在python中找到fscanf的等价物。在

对于What is the equivalent of Matlab 'fscanf' in Python?numpy.loadtxt需要{}。这不适合我的情况。在


Tags: ofthe数据innumpyis情况what
2条回答

遍历文件中的行,就像

for line in open("file.txt"):
     parse(line)

parse方法是一种将行作为输入并输出整数、浮点或整数列表的方法。在

对于整数-gt;var = int(line)

对于float->;var = float(line)

对于INT列表->;var = map(int, line.split())

对于矩阵->;请考虑阅读“想要一个m X n矩阵”。 所以从上面的循环中读入m行,就像-

^{pr2}$
with open('471220580.txt') as text_file:
    all_numbers = text_file.read().split("\n")
    all_numbers = filter(None, all_numbers)
    #the all_numbers list contains all the distinct values from the file
    #Now to initialize various variables you can use following methods:

    #Method1:
    NELEM = all_numbers[0]
    NPION = all_numbers[1]
    #and so on ... 

    #Note: Keep in mind that the values stored in these variables is of type str


   #Method2:
   NELEM, NIPON ,... = all_numbers

Method1相比,使用Method1的优点是可以在method1中使用类型转换,而实现这一点的方法是使用var1 = type(var)

^{pr2}$

对于构成矩阵的第9-12行,我们可以将矩阵表示为列表列表。在

^{3}$

相关问题 更多 >