0

I need to join several append values. Tried as follows

     lines1.append(resnum[i])
     lines1.append(resname[i])
     lines1.append(resnum[j])
     lines1.append(resname[j])
     lines1.append(j-i)
     lines1.append(r1)
     s1 = '  '.join(map(str,lines1))
     print s1
     sv = open("1.out","w")
     sv.write('  '.join(map(str,lines1)))
     sv.close()

But it is printing everything in one line as follows.

     1  AAA  2  BBB  1  3.83433240604  2  AAA  3  BBB  1  3.82626841714  3  AAA  4  BBB  1  3.82807980586  4  AAA  5  BBB  1  3.86017836375  5  AAA  6  BBB  1  3.83235241073  6  AAA  7  BBB 3.76532115

If I try to use following.

     sv.write('\n'.join(map(str,lines1)))

I get the output as follows.

     1
     AAA
     2
     BBB
     1
     3.83433240604
     ..........
     ..........

How to get the output as follows

     1     AAA      2      BBB      1      3.83433240604
     2     AAA      3      BBB      1      3.83433240604
     ...................................................
     ...................................................
4

3 回答 3

1

Ok, I'll explain my reasoning, and we can see where we diverge. I can't really use the above code unless I have a file sample because you have a lot of conditionals.

This is my interpretation of what your data looks like as the point where you are about to organize your computed data:

resname = ['ZZZ','AAA','BBB']
resnum = [0,1,2]
i = 1
j = 2
r1 = 3.1415926

So one line of your desired printout could be:

lines1 = [resnum[i], resname[i], resnum[j], resname[j], j-1, r1]

Maybe modify your code so that it goes something like:

for i in range(0,len(x)):
    all_lines = []
    for j in range(i+1,len(x)):
        lines1 = [resnum[i], resname[i], resnum[j], resname[j], j-1, r1]
        s1 = '  '.join(map(str,lines1))
        all_lines.append(s1)

with open('yourfile.txt', 'w') as f:
    for line in all_lines:
        f.write(line+'\n')

Try this one?

于 2013-09-12T18:23:21.500 回答
0

您想要一个列表列表,而不是单个列表。改变这个:

          lines1.append(resnum[i])
          lines1.append(resname[i])
          lines1.append(resnum[j])
          lines1.append(resname[j])
          lines1.append(j-i)
          lines1.append(r1)

进入这个:

          interim = []
          interim.append(resnum[i])
          interim.append(resname[i])
          interim.append(resnum[j])
          interim.append(resname[j])
          interim.append(j-i)
          interim.append(r1)
          lines1.append(interim)
于 2013-09-12T17:10:53.683 回答
0

以下对我有用。

     sv1 = open('1.out','w')
     sv1.write( ("%s     %s      %s      %s      %s      %s\n") % (resnum[i], resname[i], resnum[j], resname[j], (j-i),r1))

谢谢您的帮助。

于 2013-09-13T05:03:21.290 回答