[英]How can I print empty space for every list element which is equal to zero without changing the original list?
So I am trying to make a numerical tic tac toe game, where you input numbers and you win if it adds up to 15 horizontally/vertically/diagonally所以我正在尝试制作一个数字井字游戏,你输入数字,如果水平/垂直/对角线加起来为 15,你就赢了
at first, I just put zeros into an empty list.起初,我只是将零放入一个空列表中。 But eventually, I am gonna replace the zeros with numbers greater than zero.
但最终,我要用大于零的数字替换零。
I want to print the tic tac toe in this format:我想以这种格式打印井字游戏:
0 1 2 0 | | ----------- 1 | | ----------- 2 | |
so I used this code -所以我使用了这个代码 -
print(" 0 1 2 ")
for row in range(self.size):
print(" {0} {1} | {2} | {3} ".format(row, self.board[row][0], self.board[row][1], self.board[row][2]))
if row < 2:
print(' -----------')
but it prints out但它打印出来
0 1 2
0 0 | 0 | 0
-----------
1 0 | 0 | 0
-----------
2 0 | 0 | 0
I want to print empty space where there is zero in the list (without changing the actual list) so if the element in the list is greater than 0 then we print it else we print empty space我想打印列表中为零的空白空间(不更改实际列表),因此如果列表中的元素大于 0,则我们打印它,否则我们打印空白空间
One solution to the problem is this:该问题的一种解决方案是:
print(" 0 1 2 ")
for row in range(self.size):
print(" {0} {1} | {2} | {3} ".format(row, self.board[row][0] if self.board[row][0]> 0 else ' ', self.board[row][1] if self.board[row][1]> 0 else ' ', self.board[row][2] if self.board[row][2]> 0 else ' '))
if row < 2:
print(' -----------')
But in this case, the line has more than 120 characters which is not acceptable.但在这种情况下,该行超过 120 个字符是不可接受的。 I also do not want to use a for loop within another for loop because that will only increase the complexity and run time
我也不想在另一个 for 循环中使用 for 循环,因为这只会增加复杂性和运行时间
what can I do?我能做什么?
i tried to doodle it, its not pythonic yet but output looks good我试着涂鸦它,它不是 pythonic 但输出看起来不错
board = [[0,0,2],[0,1,0],[0,7,0]]
print(' 0 | 1 | 2')
print('---------------------')
rowCount = 0
for eachRow in board:
temp = " | ".join(str(x) for x in eachRow)
temp = temp.replace("0", " " )
print(str(rowCount) + ' | ' + temp)
print('---------------------')
rowCount = rowCount + 1
You could try to use list comprehension to reduce number of characters, but it unfortunately does not help with the complexity reduction.您可以尝试使用列表理解来减少字符数,但不幸的是它无助于降低复杂性。 Please keep in mind that this is just used as an example.
请记住,这仅用作示例。
board = np.zeros((3,3))
print(" 0 1 2 ")
for row in range(3):
a = [board[row][i] if board[row][i] else "" for i in range(3)]
print(" {0} {1} | {2} | {3} ".format(row, a[0], a[1], a[2] ))
if row < 2:
print(' -----------')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.