Modifying output of for loop in Python - python

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..

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:

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=',')

Related

How to delete "," at the end of the program python set

l = {"John","Evan"}
for i in l:
print(i,end=",")
How to get python to output: jhon,evan not: jhon,evan, ?
You can join strings (https://docs.python.org/3/library/stdtypes.html#str.join) to achieve this result:
print(','.join(l))
Will print: jhon,even.
If you had a list instead of a set, you could iterate by index and then prepend a comma starting with the second element.
l = {"John", "Evan"}
names = list(l)
for idx in range(len(names)):
if idx > 0:
print(",", end="")
print(names[idx], end="")
# John,Evan

how can I convert the for-while loop into a for-for loop and achieve the same output?

This code successfully prints a youtube play button
rows = 6
symbol = '\U0001f34a'
for i in range(rows):
for j in range(i+1):
print('{'+symbol+'}', end = '')
print()
for x in range(rows):
while x < 5:
print('{'+symbol+'}', end = '')
x+=1
print()
I tried to change the while loop into a for loop and print a "upside-down" right triangle. but it doesnt work.
rows = 6
symbol = '\U0001f34a'
for i in range(rows):
for j in range(i+1):
print('{'+symbol+'}', end = '')
print()
for x in range(rows):
for x in range(5):
print('{'+symbol+'}', end = '')
print()
Your second loop is always in range(5) so it will not print the desired output.
Firstly, you can use your 1st loop to set up the second, but it will be the same as above, and wont make a descending order. In order to do that, I reversed the 1st range :
for x in range(rows)[::-1]: # Reverse the range
for y in range(x): # Use 1st loop variable as parameter
print('{'+symbol+'}', end = '')
Output, with a 'O' since I didnt set up the encoding for your symbol
{O}
{O}{O}
{O}{O}{O}
{O}{O}{O}{O}
{O}{O}{O}{O}{O}
{O}{O}{O}{O}{O}{O}
{O}{O}{O}{O}{O}
{O}{O}{O}{O}
{O}{O}{O}
{O}{O}
{O}
ok thanks for the help guys I see where I messed up.when i was converting the while loop to a for loop I was supposed to find the range in the iteration of the outer for loop. Here is my new code that works perfectly
rows = 6
symbol = '\U0001f34a'
for i in range(rows):
for j in range(i+1):
print('{'+symbol+'}', end = '')
print()
for x in range(rows,0,-1):
for e in range(x,1,-1):
print('{'+symbol+'}', end = '')
print()
It was fun to create, so here is my code that works.
The second for loop start to max length and end at 0 with a step of -1, with this you can create a for loop that decreases
for i in range(rows):
print('{'+symbol+'}'*(i+1))
for i in range(rows,0,-1):
print('{'+symbol+'}'*(i-1))

i have a problem with strings and for loop in python

I have a string and I saved it inside a variable.
I want to change even characters to capitalize with for loop.
so i give my even characters and capitalized it. But
i cant bring them with odd characters .
can someone help me?
here is my code:
name = "mohammadhosein"
>>> for even in range(0, len(name), 2):
... if(even % 2 == 0):
... print(name[even].title(), end=' ')
...
M H M A H S I >>>
>>> ###### I want print it like this:MoHaMmAdHoSeIn```
I assume you are quite new to programing, so use a the following for loop:
name = "mohammadhosein"
output = ''
for i, c in enumerate(name):
if i % 2 == 0:
output += c.upper()
else:
output += c
# output will be 'MoHaMmAdHoSeIn'
enumerate will give you a pair of (i, c) where i is an index, starting at 0, and c is a character of name.
If you feel more comfortable with code you can use a list comprehension and join the results as follows:
>>> ''.join([c.upper() if i % 2 == 0 else c for i, c in enumerate(name)])
'MoHaMmAdHoSeIn'
As #SimonN has suggested, you just needed to make some small changes to your code:
for index in range(0, len(name)):
if(index % 2 == 0):
print(name[index].upper(), end='') # use upper instead of title it is more readable
else:
print(name[index], end='')
print()

Printing out the output in separate lines in python

I am trying to print out the output of the maximum route each in a separate line.
The code is here:
def triangle(rows):
PrintingList = list()
for rownum in range (rows ):
PrintingList.append([])
newValues = map(int, raw_input().strip().split())
PrintingList[rownum] += newValues
return PrintingList
def routes(rows,current_row=0,start=0):
for i,num in enumerate(rows[current_row]):
if abs(i-start) > 1:
continue
if current_row == len(rows) - 1:
yield [num]
else:
for child in routes(rows,current_row+1,i):
yield [num] + child
testcases = int(raw_input())
output = []
for num in range(testcases):
rows= int(raw_input())
triangleinput = triangle(rows)
max_route = max(routes(triangleinput),key=sum)
output.append(sum(max_route))
print '\n'.join(output)
I tried this:
2
3
1
2 3
4 5 6
3
1
2 3
4 5 6
When i try to output out the value, i get this:
print '\n'.join(output)
TypeError: sequence item 0: expected string, int found
How do change this? Need some guidance...
Try this:
print '\n'.join(map(str, output))
Python can only join strings together, so you should convert the ints to strings first. This is what the map(str, ...) part does.
#grc is correct, but instead of creating a new string with newlines, you could simply do:
for row in output:
print row

Python trouble exiting a 'while' loop for simple script

I wrote a script to reformat a tab-delimited matrix (with header) into a "long format". See example below. It performs the task correctly but it seems to get stuck in an endless loop...
Example of input:
WHO THING1 THING2
me me1 me2
you you1 you2
Desired output:
me THING1 me1
me THING2 me2
you THING1 you1
you THING2 you2
Here is the code:
import csv
matrix_file = open('path')
matrix_reader = csv.reader(matrix_file, delimiter="\t")
j = 1
while j:
matrix_file.seek(0)
rownum = 0
for i in matrix_reader:
rownum+=1
if j == int(len(i)):
j = False
elif rownum ==1:
header = i[j]
else:
print i[0], "\t",header, "\t",i[j]
j +=1
I think it has to do with my exit command (j = False). Any ideas?
edit: Thanks for suggestions. I think a typo in my initial posting led to some confusion, sorry about that For now I have employed a simple solution:
valid = True
while valid:
matrix_file.seek(0)
rownum = 0
for i in matrix_reader:
rownum+=1
if j == int(len(i)):
valid = False
etc, etc, etc...
Your j += 1 is outside the while loop, so j never increases. If len(i) is never less than 2, then you'll have an infinite loop.
But as has been observed, there are other problems with this code. Here's a working version based on your idiom. I would do a lot of things differently, but perhaps you'll find it useful to see how your code could have worked:
j = 1
while j:
matrix_file.seek(0)
rownum = 0
for i in matrix_reader:
rownum += 1
if j == len(i) or j == -1:
j = -1
elif rownum == 1:
header = i[j]
else:
print i[0], "\t", header, "\t", i[j]
j += 1
It doesn't print the rows in the order you wanted, but it gets the basics right.
Here's how I would do it instead. I see that this is similar to what Ashwini Chaudhary posted, but a bit more generalized:
import csv
matrix_file = open('path')
matrix_reader = csv.reader(matrix_file, delimiter="\t")
headers = next(matrix_reader, '')
for row in matrix_reader:
for header, value in zip(headers[1:], row[1:]):
print row[0], header, value
j+=1 is outside the while loop as senderle's answer says.
other improvements can be:
int(len(i)) ,just use len(i) ,as len() always returns a int so no need of int() around
it
use for rownum,i in enumerate(matrix_reader): so now there's no
need of handling an extra variable rownum, it'll be incremented by
itself.
EDIT: A working version of your code, I don't think there's a need of while here, the for loop is sufficient.
import csv
matrix_file = open('data1.csv')
matrix_reader = csv.reader(matrix_file, delimiter="\t")
header=matrix_reader.next()[0].split() #now header is ['WHO', 'THING1', 'THING2']
for i in matrix_reader:
line=i[0].split()
print line[0], "\t",header[1], "\t",line[1]
print line[0], "\t",header[2], "\t",line[2]

Categories

Resources