[英]Python Check a 2d list for empty strings?
我一直試圖找出這個問題多個小時仍然沒有運氣。 我正在用Python編寫Connect4用於學校作業,我需要一個檢查電路板是否已滿的功能。
這是我的初始化函數
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)
你的isFull
方法的邏輯是不正確的。
在當前代碼中,一旦找到非空單元格,就會從isFull
返回True
。 那是不對的。 你應該做相反的事情。
您應該執行kobejohn之前發布的內容:一旦找到空單元格,就返回False
。
如果可能的話,在Python中你應該沒有索引,並使用Python自然循環,就像kobejohn發布的代碼一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.