简体   繁体   English

在python的不同行中打印输出

[英]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. Python只能将字符串连接在一起,因此您应该先将int转换为字符串。 This is what the map(str, ...) part does. 这就是map(str, ...)部分所做的。

@grc is correct, but instead of creating a new string with newlines, you could simply do: @grc是正确的,但是您可以简单地执行以下操作:不必使用换行符创建新的字符串:

for row in output:
    print row

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM