What should I do to make the data I expect like the one below?
#Target Data
test_list = [
['.', '.', '.'],
['.', '#', '.'],
['.', '.', '.']
]
# expected data
test_list = [
['.', '#', '.'],
['#', '#', '#'],
['.', '#', '.']
]
Below are some of the actions I've tried.
However, some of the expected values are not substituted, and the extra values are substituted.
We are unable to find a solution at this stage, so if anyone knows, please let us know.
#Target Data
test_list = [
['.', '.', '.'],
['.', '#', '.'],
['.', '.', '.']
]
for i in range(len(test_list))):
for jin range(len(test_list))):
try:
if test_list[i][j+1]=='#' or test_list[i][j-1]=='#' or test_list[i-1][j]=='#' or test_list[i+1][j]=='#':
test_list[i][j]='#'
except IndexError:
pass
print(test_list[0])
print(test_list[1])
print(test_list[2])
# output result
['.', '#', '.']
['#', '#', '.']
['#', '#', '.']
The script binary_dilation()
is easy.
scipy.ndimage.binary_dilation—SciPy Manual
import numpy as np
from scope.ndimage import binary_dilation
default_closs(lst,s):
arr = np.array(lst)
arr [binary_dilation(arr==s)] = s
return ar.tolist()
Considering the possibility of multiple #
, how about the following code?
test_list=[
['.', '.', '.'],
['.', '#', '.'],
['.', '.', '.']
]
indexes = [ ]
for i in range(len(test_list))):
for jin range (len(test_list[0])):
if test_list[i][j]=="#":
indexes.append(i-1,j))
indexes.append(i,j-1))
indexes.append(i,j+1))
indexes.append(i+1,j))
for(i,j)in indexes:
try:
test_list[i][j]="#"
except IndexError:
pass
print(test_list)
If you don't mind using numpy,
def set_closs(lst,s):
import numpy as np
ary=np.array(lst)
for idx in zip (*np.where(ary==s)):
aary [max(0,idx[0]-1): idx[0]+2,idx[1]]=ary [idx]
ary [idx[0], max(0, idx[1]-1): idx[1]+2] = ary [idx]
returnary.tolist()
# Target Data
test_list = [
['.', '.', '.'],
['.', '#', '.'],
['.', '.', '.']
]
out_list = set_closs(test_list, '#')
print(*out_list, sep='\n')
"""
['.', '#', '.']
['#', '#', '#']
['.', '#', '.']
"""
test_list = [
['.', '.', '.', '.'],
['.', '#', '.', '.'],
['.', '.', '#', '.'],
['.', '.', '.', '.']
]
out_list = set_closs(test_list, '#')
print(*out_list, sep='\n')
"""
['.', '#', '.', '.']
['#', '#', '#', '.']
['.', '#', '#', '#']
['.', '.', '#', '.']
"""
© 2024 OneMinuteCode. All rights reserved.