gpt4 book ai didi

Python 检查二维列表中是否有空字符串?

转载 作者:行者123 更新时间:2023-11-30 23:30:36 25 4
gpt4 key购买 nike

我花了几个小时试图解决这个问题,但仍然没有成功。我正在为一项学校作业用 Python 编写 Connect4,我需要一个函数来检查板是否已满。

这是我的init函数

    def __init__( self, width, height ): 
self.width = width
self.height = height
self.data = [] # this will be the board

for row in range( self.height ):
boardRow = []
for col in range( self.width ):
boardRow += [' ']
self.data += [boardRow]

我的repr功能

    def __repr__(self): 
#print out rows & cols
s = '' # the string to return
for row in range( self.height ):
s += '|' # add the spacer character
for col in range( self.width ):
s += self.data[row][col] + '|'
s += '\n'

s += '--'*self.width + '-\n'

for col in range( self.width ):
s += ' ' + str(col % 10)
s += '\n'

return s

我的 isFull 函数有什么

    def isFull(self):
# check if board is full
for row in range(0,(self.height-(self.height-1))):
for col in range(0,self.width):
if (' ') not in self.data[row][col]:
return True

我想检查一下数据列表中是否有这个“”(空格)。至少我认为这是我的问题,我没有 python 经验,所以我可能误读了我的问题。如果有人有任何想法,我很乐意倾听。

最佳答案

如果有空间,就表示棋盘未满?

各种版本:

# straightforward but deep
def is_full(self):
for row in self.data:
for cell in row:
if cell == ' ':
return False
return True
<小时/>
# combine the last two
def is_full(self): # python functions/methods are usually lower case
for row in self.data: # no need to index everything like c
if any(cell == ' ' for cell in row): # any/all are convenient testers
return False # if you find even one, it's done.
return True # if you couldn't disqualify it, then it looks full
<小时/>
# one line, not especially readable
def is_full(self):
return not any(cell == ' ' for row in d for cell in row)

关于Python 检查二维列表中是否有空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com