循环打印

时间:2011-09-19 17:38:42

标签: python printing for-loop

我有以下文件我试图操纵。

 1  2 -3 5  10  8.2
 5  8  5 4  0   6
 4  3  2 3 -2   15
 -3 4  0 2  4   2.33
 2  1  1 1  2.5 0
 0  2  6 0  8   5

该文件只包含数字。

我正在尝试编写一个程序来相互减去行并将结果打印到文件中。我的程序在下面,dtest.txt是输入文件的名称。该计划的名称为make_distance.py

from math import *

posnfile = open("dtest.txt","r")
posn = posnfile.readlines()
posnfile.close()

for i in range (len(posn)-1):
    for j in range (0,1):
        if (j == 0):
            Xp = float(posn[i].split()[0])
            Yp = float(posn[i].split()[1])
            Zp = float(posn[i].split()[2])

            Xc = float(posn[i+1].split()[0])
            Yc = float(posn[i+1].split()[1])
            Zc = float(posn[i+1].split()[2])
        else:
            Xp = float(posn[i].split()[3*j+1])
            Yp = float(posn[i].split()[3*j+2])
            Zp = float(posn[i].split()[3*j+3])

            Xc = float(posn[i+1].split()[3*j+1])
            Yc = float(posn[i+1].split()[3*j+2])
            Zc = float(posn[i+1].split()[3*j+3])

        Px = fabs(Xc-Xp)
        Py = fabs(Yc-Yp)
        Pz = fabs(Zc-Zp)
        print Px,Py,Pz

程序正在正确计算值,但是当我尝试调用程序来编写输出文件时,

mpipython make_distance.py > distance.dat

输出文件(distance.dat)只包含3列,当它应该包含6时。如何告诉程序将要打印的列移动到每个步骤j = 0,1,.... / p>

对于j = 0,程序应输出到前3列,对于j = 1,程序应输出到后3列(3,4,5),依此类推。

最后,len函数给出了输入文件中的行数,但是,哪个函数给出了文件中的列数?

感谢。

3 个答案:

答案 0 :(得分:5)

,语句的末尾添加print,它不会打印换行符,然后当您退出for循环时添加一个print以移至下一个行:

for j in range (0,1):
    ...

    print Px,Py,Pz,
print

假设所有行的列数相同,您可以使用len(row.split())获取列数。

另外,你肯定可以缩短你的代码,我不确定j的目的是什么,但以下内容应该等同于你现在正在做的事情:

    for j in range (0,1):
        Xp, Yp, Zp = map(float, posn[i].split()[3*j:3*j+3])
        Xc, Yc, Zc = map(float, posn[i+1].split()[3*j:3*j+3])
        ...

答案 1 :(得分:1)

您不需要:

  • 使用numpy
  • 立即阅读整个文件
  • 知道有多少列
  • 在打印声明结尾处使用尴尬的逗号
  • 使用列表下标
  • 使用math.fabs()
  • 明确关闭您的文件

试试这个(未经测试):

with open("dtest.txt", "r") as posnfile:
    previous = None
    for line in posnfile:
        current = [float(x) for x in line.split()]
        if previous:
            delta = [abs(c - p) for c, p in zip(current, previous)]
            print ' '.join(str(d) for d in delta)
        previous = current

答案 2 :(得分:0)

以防万一dtest.txt变大,您不想重定向输出,而是写入distance.dat,尤其是如果您想使用numpy。感谢@John指出我在旧代码中的错误; - )

import numpy as np
pos = np.genfromtxt("dtest.txt")
dis = np.array([np.abs(pos[j+1] - pos[j]) for j in xrange(len(pos)-1)])
np.savetxt("distance.dat",dis)
相关问题