猿问

python中的格式列表

我有一个包含数字25-1的列表。我正在尝试像游戏板一样打印出来,其中所有数字都匹配:

我发现了如何通过执行以下操作将行添加到列表中:


_b = map(str, board)

_board = ' | '.join(_b)

而且我知道如何在每行上打印5个数字。但是我无法使所有数字都对齐。有没有办法做到这一点?


手掌心
浏览 185回答 3
3回答

jeck猫

board = range(1,26) #the gameboardfor row in [board[i:i+5] for i in range(0,22,5)]: #go over chunks of five&nbsp; &nbsp; print('|'.join(["{:<2}".format(n) for n in row])+"|") #justify each number, join by |&nbsp; &nbsp; print("-"*15) #print the -'s产生>>>&nbsp;1 |2 |3 |4 |5 |---------------6 |7 |8 |9 |10|---------------11|12|13|14|15|---------------16|17|18|19|20|---------------21|22|23|24|25|---------------或使用grouper@abarnert建议的配方:for row in grouper(5, board):

隔江千里

只是为了好玩,这里有一个1-liner来创建编号的行:['|'.join([str(y).center(4) for y in x]) for x in map(None,*[reversed(range(1,26))]*5)]稍微分解一下,添加行,仍然不是一个干净的答案:nums = map(None,*[reversed(range(1,26))]*5)rows = ['|'.join([str(y).center(4) for y in x]) for x in nums]board = ('\n'+'-'*len(rows[0])+'\n').join(rows)print board
随时随地看视频慕课网APP

相关分类

Python
我要回答