从fi加载浮点数矩阵

2024-05-29 11:34:03 发布

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

我有一些数据

  1  2  3  4
  3  5  6  7
  2  8  9  10

我的密码是

    #!/bin/usr/python
    file=open("fer.txt","r")
    M=[]
    P=[]
    K=[]
    def particle(M,P,K):
        for line in file:
            y=line.split()
            M.append(y)
        for i in range(3):
            for j in range(4):
                P.append(float(M[i][j]))
            K.append(P)
        return K
   print(particle(M,P,K))

然后我得到了

[[1.0, 2.0, 3.0, 4.0, 3.0, 5.0, 6.0, 7.0, 2.0, 8.0, 9.0, 10.0], [1.0, 
2.0, 3.0, 4.0, 3.0, 5.0, 6.0, 7.0, 2.0, 8.0, 9.0, 10.0], [1.0, 2.0, 3.0, 
4.0, 3.0, 5.0, 6.0, 7.0, 2.0, 8.0, 9.0, 10.0]]

但我有或者我想要这样的东西

[[1.0, 2.0, 3.0, 4.0,], [3.0, 5.0, 6.0, 7.0],[ 2.0, 8.0, 9.0, 10.0]]

编辑为重复标志:我不明白这是一个如何重复的问题我。我在问不同的问题,我也在试图理解为什么我的代码不能工作。你知道吗


Tags: 数据intxt密码forbinusrdef
2条回答

第一个答案是正确的,但如果你想在一行:


#sample.txt content: 
1  2  3  4
3  5  6  7
2  8  9  10

#code:

In [12]: d = open('sample.txt').readlines()
    ...: result =  [map(float, x.split()) for x in d]

输出:

In [13]: result
Out[13]: [[1.0, 2.0, 3.0, 4.0], [3.0, 5.0, 6.0, 7.0], [2.0, 8.0, 9.0, 10.0]]

使用迭代。可以使用map将list的所有元素转换为float。你知道吗

例如:

res = []
with open(filename2) as infile:
    for line in infile:
        line = line.strip()
        res.append(map(float, line.split()))
print(res)

输出:

[[1.0, 2.0, 3.0, 4.0], [3.0, 5.0, 6.0, 7.0], [2.0, 8.0, 9.0, 10.0]]

相关问题 更多 >

    热门问题