[英]Find and replace all matching elements in a 2d list with a value
I have a 2d list [[1134],[2221],[3321],[2324]].我有一个二维列表 [[1134]、[2221]、[3321]、[2324]]。 It is outputted as它输出为
1 1 3 4
2 2 2 1
3 3 2 1
2 3 2 4
The user enters a row(0-3) and column(0-3).用户输入行(0-3)和列(0-3)。 If the user enters row=1 and column=2如果用户输入 row=1 和 column=2
1 1 3 4
2 2(2) 1
3 3 2 1
2 3 2 4
The program should find all matching values from that point and then replace them with 'x'.该程序应从该点找到所有匹配值,然后将它们替换为“x”。 Matches can be horizontal or vertical.匹配可以是水平的或垂直的。 Must be at least n in a row to match.必须至少连续 n 个才能匹配。 So the list would look like this:所以列表看起来像这样:
1 1 3 4
x x x 1
3 3 x 1
2 3 x 4
Please help how would I do this.请帮助我该怎么做。
So far I have tried:到目前为止,我已经尝试过:
def check_matching(row,col,list):
SIZE=len(list)
n=3
upcount =0
downcount =0
leftcount =0
rightcount =0
#Up Match
if row-n>=-1:
upcount-=1
for i in range(row, -1, -1):
#print(list[i][col])
if list[i][col] == list[row][col]:
upcount+=1
#Down Match
if row+n<=SIZE:
downcount-=1
for i in range(row, SIZE):
#print(list[i][col])
if(list[i][col] == list[row][col]):
downcount+= 1
#Left Match up
if col-n>=-1:
leftcount-=1
for i in range(col, -1, -1):
#print(list[row][i])
if(list[row][i] == list[row][col]):
leftcount+=1
#Right Match
if col+n<=SIZE:
rightcount-=1
for i in range(col, SIZE):
#print(list[row][i])
if(list[row][i] == list[row][col]):
rightcount+=1
if upcount>=n-1 or downcount>=n-1 or leftcount>=n-1 or rightcount>=n-1:
print ("match")
if upcount>=n-1:
for i in range(col, -1, -1):
#print(list[row][i])
if(list[row][i] == list[row][col]):
list[row][i]='.'
Please help.请帮忙。 Thank You.谢谢你。
I made a totally different version of your code and that's what I got:我制作了一个完全不同的代码版本,这就是我得到的:
def check_matching(row, col, arr):
value = arr[row][col]
for i, rows in enumerate(arr):
for j, cols in enumerate(rows):
if cols == value and (i == row or j == col):
arr[i][j] = "x"
return arr
print(check_matching(1, 2, [[1, 1, 3, 4],[2, 2, 2, 1],[3, 3, 2, 1],[2, 3, 2, 4]]))
The output will be a matrix with this format: output 将是具有以下格式的矩阵:
[[1, 1, 3, 4],
['x','x','x', 1],
[ 3, 3, 'x', 1],
[ 2, 3, 'x', 4]]
I hope I understood your problem correctly我希望我正确理解你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.