Home > other >  Looping on each line and each position in python
Looping on each line and each position in python

Time:04-13

I'm stuck in a small looping problem. I have a file with different positions.

p = [10, 11, 16]

I have an input (have 5 line for example) file like this:

s = """BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB
BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB
BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB
BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB
BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB"""

Now I like to make a loop in python which will print only those positions given in p from each line in s.

The desired output will be:

DDA
DDA
DDA
DDA
DDA

Now, this is my code:

p=np.loadtxt('positions')
s=np.loadtxt('s')
for i in range (0, len(s)): 
    for i in p:  
        print(line [int(i)], end='')

output is : DDADDADDADDADDA

How do I convert this output to:

DDA
DDA
DDA
DDA
DDA

CodePudding user response:

you can try this:

p=np.loadtxt('positions')
s=np.loadtxt('s')
for i in range (0, len(s)): 
    for i in p:  
        print(line [int(i)], end='')
    print()

this way you add a linebreak at the end of the outer for-loop

CodePudding user response:

You just have to print each iteration in seperate line, then just use print statement like this

print(line [int(i)], end='\n')
  • Related