[英]How to find a char in a list of lists?
I'm writing code that creates a crossword and I want code that finds a specific char in a table.我正在编写创建填字游戏的代码,我想要在表中找到特定字符的代码。 so for example if the board contains the word 'car' and I'm looking for the char 'a', it would return the value for the row and column.
例如,如果板子包含单词“car”并且我正在寻找字符“a”,它将返回行和列的值。 This is the code I have for printing the board and the first word.
这是我打印电路板和第一个单词的代码。
board = [[' '] * 20 for i in range(20)]
def printboard(board):
columns = '01234567890123456789'
rows = '_' * 20
print(' ' + columns)
print(' ' + rows)
for i in range(20):
s = ''.join(board[i])
print('|' + s +'|' + str(i))
print(' ' + rows)
print(' ' + columns)
def addFirstWord(board, word):
n = len(word)
if n > 20:
return False
row = 10
col = (20 - n) // 2
board[row][col:col+n] = word
return True
addFirstWord(board, 'car')
printboard(board)
I think I have to write a loop that checks every index in the board but i'm not sure how to write it.我想我必须编写一个循环来检查板上的每个索引,但我不确定如何编写它。 Thanks
谢谢
This should work:这应该有效:
def findCharacter(board, char):
# Loop through all rows and columns
for i, c in enumerate(board):
for j, r in enumerate(c):
# If we find the character, return it
if r == char:
return j, i
For example:例如:
>>> board = [[' '] * 20 for i in range(20)]
>>> addFirstWord(board, 'car')
>>> findCharacter(board, 'c')
(8, 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.