Python- IndexError:列表索引超出范围,而在for循环中 [英] Python- IndexError: list index out of range, while in for loop
问题描述
我是python的新手.我正在尝试编写代码以从文本文件中获取输入,例如
I'm new to python. I am trying to write a code to take input from text file like
6 6
* o o o o *
o o * o o o
o o * o o *
o o * o o o
o o o o * o
o o o o o o
计算每个字符串附近的"*"数,并用新的计数更新每个字符串,例如:
and count the number of "*" near each string and update each string with the new count like:
6 6
* 2 1 1 1 *
1 3 * 2 2 2
0 3 * 3 1 *
0 2 * 2 2 2
0 1 1 2 * 1
0 0 0 1 1 1
并在output.txt上更新它.到目前为止,我的代码一直在接受输入并提供行,列和矩阵,但是一旦我进入列表进行计数,就无法给出错误
And update this on an output.txt. Until now my code is taking input and providing rows, column, and matrix but as soon as I get into the list to count, it fails giving error
if matrix[num_rows][num_columns][1] == "x":
IndexError:列表索引超出范围
IndexError: list index out of range
我的代码段:
def parse_in(input_name):
list_of_lists = []
with open(input_name,"r") as f:
for line in f:
with open(input_name) as f:
num_rows, num_columns = [int(x) for x in next(f).split()]
lines = f.read().splitlines()
# in alternative, if you need to use the file content as numbers
matrix = []
print(lines)
for x in lines:
matrix.append(x.split(' '))
print(matrix)
return matrix, num_rows, num_columns
def detector(matrix, num_rows, num_columns):
mine_count = 0
# For every every space around the square, including itself
for r in range(num_rows):
for c in range(num_columns):
# If the square exist on the matrix
if 0 <= num_rows + r <= 2 and 0 <= num_columns + c <= 2:
# If the square contains a mine
if matrix[r][c] == "*":
# Raise the mine count
mine_count = mine_count + 1
# If the original square contains a mine
if matrix[r][c] == "*":
print(mine_count)
# Lower the mine count by 1, because the square itself having a mine shouldn't be counted
mine_count = mine_count - 1
print(mine_count)
return mine_count
def parse_out(output_name, my_solution):
pass
def my_main(input_name, output_name):
# 1. We do the parseIn from the input file
lines, num_rows, num_columns = parse_in(input_name)
# 2. We do the strategy to solve the problem
my_solution = detector(lines, num_rows, num_columns)
# 3. We do the parse out to the output file
parse_out(output_name, my_solution)
if __name__ == '__main__':
# 1. Name of input and output files
input_name = "input_2.txt"
output_name = "output.txt"
# 2. Main function
my_main(input_name, output_name)
推荐答案
首先阅读文本文件,然后将行内容放入numpy数组中:
First read the text file and get the line contents into a numpy array, with this :
with open('test1.txt', 'r') as f:
all_lines = f.readlines()
mat_shape = tuple(map(int, all_lines[0].split()))
lines = [i.strip().split() for i in all_lines[1:]]
lines = np.array(lines)
读取文本文件的第一行,进行拆分,将它们映射为int并将其保存在一个元组中,以便稍后使用它调整矩阵大小.
Read the first line of the text file, split, map them into int and keep it in a tuple as we use it to resize our matrix later.
lines
就像这样:
[['*' 'o' 'o' 'o' 'o' '*']
['o' 'o' '*' 'o' 'o' 'o']
['o' 'o' '*' 'o' 'o' '*']
['o' 'o' '*' 'o' 'o' 'o']
['o' 'o' 'o' 'o' '*' 'o']
['o' 'o' 'o' 'o' 'o' 'o']]
使用此函数获取矩阵每个单元的相邻项:
Get the neighbor items for each cell of the matrix, with this function :
def get_neighbours(lines, cell):
row, col = cell
row_max = len(lines)
col_max = len(lines[0])
cell_cont = lines[row][col]
if cell_cont!="*":
return [lines[row_d + row][col_d + col] for col_d in [-1,0,1] if (0 <= (col_d + col) < col_max) or (col_d == 0 and row_d==0) for row_d in [-1,0,1] if 0 <= (row_d + row) < row_max ].count('*')
else:
return '*'
该函数采用整个矩阵和一个特定的单元格,该单元格是行号和列号的元组.如果单元格中有星星,则仅返回'*'
,否则返回整数-相邻相邻单元格中的星星数.
The function takes whole matrix and a particular cell which is a tuple of row and column number. It returns only '*'
if there is a star in the cell, otherwise an integer - the number of stars in the adjacent neighbor cells.
现在创建一个新数组,并为矩阵的每个单元格调用此函数:
Now create a new array, and call this function for each cell of the matrix :
new = []
for i,_ in enumerate(lines):
for j,_ in enumerate(lines[i]):
new.append(get_neighbours(lines, (i,j)))
new = np.array(new)
如果您现在通过以下方式将此矩阵重塑为所需格式:
If you now reshape this matrix into the desired format by this :
new = new.reshape(mat_shape)
它变成了:
[['*' '2' '1' '1' '1' '*']
['1' '3' '*' '2' '2' '2']
['0' '3' '*' '3' '1' '*']
['0' '2' '*' '3' '2' '2']
['0' '1' '1' '2' '*' '1']
['0' '0' '0' '1' '1' '1']]
您可以使用以下命令将其写入新的文本文件中:
You can write this into a new text file with this :
with open('new1.txt', 'w') as f:
f.write(all_lines[0])
for i in new:
f.write(' '.join(i))
f.write('\n')
它将以下内容写入new1.txt
文件:
It would write the following content into the new1.txt
file :
6 6
* 2 1 1 1 *
1 3 * 2 2 2
0 3 * 3 1 *
0 2 * 2 2 2
0 1 1 2 * 1
0 0 0 1 1 1
这篇关于Python- IndexError:列表索引超出范围,而在for循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!