Python上的数字三角形 [英] Triangle of numbers on Python

查看:1039
本文介绍了Python上的数字三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求写一个循环系统,打印以下内容:

I'm asked to write a loop system that prints the following:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0

但是,我的脚本会显示以下内容:

However, my script prints this:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 

0 1 2 3 4 5 6 7 


0 1 2 3 4 5 6 
# ... and so on

要修改的代码为:

for row in range(10):
    for column in range(row):
        print ''
    for column in range(10-row):
        print column,

推荐答案

循环太多,只需要两个循环即可:

You have too many loops, you only need two:

for row in range(10):
    for column in range(10-row):
        print column,
    print("")

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 
0 1 2 3 4 5 6 
0 1 2 3 4 5 
0 1 2 3 4 
0 1 2 3 
0 1 2 
0 1 
0 

或从将来导入的打印内容适用于python2.7和3:

Or importing print from future which will work for python2.7 and 3:

from __future__  import print_function

for row in range(10):
    for column in range(10-row):
        print(column,end=" ")
    print()

如果您想要一个班轮,可以使用join:

If you want a one liner you can use join:

print("\n".join([" ".join(map(str,range(10-row))) for row in range(10)]))

这篇关于Python上的数字三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆