Python将2048板隔开
所以我有2048板的代码:Python将2048板隔开,python,python-3.x,list,Python,Python 3.x,List,所以我有2048板的代码: count = 0 for i in range(16): print(nlist[i], end = ' ') count += 1 if count == 4: print("") count = 0 如果所有的值都是一位数,那么这就可以了: 0 0 0 8 0 4 0 0 0 0 2 2 0 0 0 0 但如果我有多个超过1位数的数字: 16 0 2 2048 8 2 32 64 2 2 0 0 2
count = 0
for i in range(16):
print(nlist[i], end = ' ')
count += 1
if count == 4:
print("")
count = 0
如果所有的值都是一位数,那么这就可以了:
0 0 0 8
0 4 0 0
0 0 2 2
0 0 0 0
但如果我有多个超过1位数的数字:
16 0 2 2048
8 2 32 64
2 2 0 0
2048 2048 4096 4096
所有的间隔都被弄乱了。这有什么解决办法吗?正如Keatinge在评论中提到的,在打印之前迭代数组并找到最长的数字
length = max(map(lambda x: len(str(x)), nlist)) + 1
我们取nlist
,计算出每一个数字作为文本时的长度,然后取最大值并加上一个(+1表示数字之间有一个空格)。然后,在循环内部,我们将要查看的数字字符串化,并根据需要添加空格
text = str(x)
text += ' ' * (length - len(text))
完整示例:
count = 0
length = max(map(lambda x: len(str(x)), nlist)) + 1
for i in range(16):
text = str(nlist[i])
text += ' ' * (length - len(text))
print(text, end = '')
count += 1
if count == 4:
print()
count = 0
避免为此编写自定义函数。有很多python包可以在一个整洁的表格中打印东西 我的建议是使用
计算最长值的长度,然后用空格填充其他值,使其长度达到我不知道如何将该解决方案放入我的代码中。为什么不使用
格式
?这样短的数字就可以居中了。你如何使用格式呢?
from prettytable import PrettyTable
t = PrettyTable(header=False, border=False)
for i in range(0,16,4):
t.add_row(range(i, i+4))
print t
# 0 1 2 3
# 4 5 6 7
# 8 9 10 11
# 12 13 14 15