我有这段代码:
def floyd(n):
count = 1
string = ""
for i in range(1,n+2):
for j in range(1,i):
string = string + " " + str(count)
count = count + 1
print(string)
string = ""
print floyd(6)
打印:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
但我希望它看起来像这样:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
你能帮我弄清楚怎么做吗?
答案 0 :(得分:6)
Python字符串实际上有一个内置的center()
方法,可以为你做到这一点。
print(string.center(total_width))
您可以提前设置total_width
:
total_width = -1
for i in xrange(0, n):
total_width += 1 + len(str((n + n * n) / 2 - i))
或者
total_width = sum(1 + len(str((n + n * n) / 2 - i)) for i in xrange(0, n)) - 1
即,与第n个三角形数字(n²+ n)÷2在同一行中的数字的字符串表示的长度之和。
答案 1 :(得分:2)
使用n
,您可以先找到最后一行,最后一个数字是(n**2 + n)/2
,因此最后一行的第一个数字是((n**2 + n)/2) - (n-1)
,现在可以使用{创建最后一行{1}}和列表理解:
str.join
现在我们可以在字符串格式中使用此行的宽度来正确地居中其他行。
<强>代码:强>
x = ((n**2 + n)/2)
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1))
<强>演示:强>
from itertools import count
def floyd(n):
x = ((n**2 + n)/2)
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1))
width = len(last_row)
c = count(1)
for x in xrange(1, n):
line = ' '.join(str(next(c)) for _ in xrange(x))
print "{:^{}}".format(line, width)
print last_row
答案 2 :(得分:-1)
def FloydT(n):
num=0
row=""
for i in range(1,n+1):
for j in range(1,i+1):
num+=1
row+=str(num)+" "
print(str.center(row,3*n)) # this line will do what you want
row=""