0

I am looping in through a file as per the code below:

for i in tree.iter():
    for j in i:
        print(j.col)
        print(j.out)
        print('\n')

Given below is the current output:

col1
out1

col2
out2

col3
out3

I am trying to have this modified as below:

col1,col2,col3
out1,out2,out3

Could anyone advice on how I could have my for loop modified. Thanks..

scott martin
  • 1,253
  • 1
  • 14
  • 36

2 Answers2

0

You can use this

print(j.col, end=',')

Edit:
By default Python adds an "\n" new line break at the end of print() functions. You can use the "end" value to change it.

I've made a makeshift version of your code to test it out

j = 0
k = 0

while j < 2:
    print("col", end=",")
    if j == 1:
        print("col")
    j += 1

while k < 2:
    print("out", end=",")
    if k == 1:
        print("out")
    k += 1

Output:

output

Roko
  • 129
  • 12
  • I added a new line at the end of each loop and have updated my initial post.. This now gives an empty break before starting the loop.. Still trying to see how I could write new row after each empty row as a new column – scott martin Nov 27 '18 at 13:55
  • I'm still new with python, but I'd do it with two loops, one for col, one for out and also add the "end" value from my answer. I hope it can help. – Roko Nov 27 '18 at 13:57
0

Python 3.x: save cols and outs into two separate lists and later print their elements (using an asterisk before the list name) separated by a comma:

cols = list()
outs = list()

for i in tree.iter():
    for j in i:
        cols.append(j.col)
        outs.append(j.out)
    print(*cols, sep=',')
    print(*outs, sep=',')
arudzinska
  • 3,152
  • 1
  • 16
  • 29
  • Is there a different between `list()` and `[]` or it's just a matter of preference? What does the asterisk do? – Guimoute Nov 27 '18 at 15:36
  • `list()` is calling a function, while `[]` is a literal syntax. The second option is slightly faster, but unless you're creating a million of lists the difference will not be noticeable and can be a matter of preference ([here](https://stackoverflow.com/questions/30216000/why-is-faster-than-list) some explanation of the time difference). Asterisk in front of a list acts as unpack operator, so it will expand the list into arguments that are passed into the print function. – arudzinska Nov 27 '18 at 15:56