用Python替换列表中的值

时间:2016-03-12 14:48:07

标签: python python-2.7

我正在编写一些代码,用'X'替换方形矩阵中的所有值,这些值大于与其相邻的值(上,下,左和右)。但是当我尝试执行它时,我得到了一个ValueError。

这是我的代码:

left_on

这是我的追溯:

n = int(raw_input().strip())
grid = []
grid_i = 0
for grid_i in xrange(n):
    grid_t = list(raw_input().strip())
    grid.append(grid_t)

for x in xrange(1, n-1):
    for y in xrange(1, n-1):
        if (int(grid[x][y]) > int(grid[x-1][y]) and int(grid[x][y]) > int(grid[x+1][y]) and int(grid[x][y]) > int(grid[x][y+1]) and int(grid[x][y] > int(grid[x][y-1]))):
            grid[x][y] = "X"

print grid

我理解错误意味着我正在尝试在Traceback (most recent call last): File "test.py", line 24, in <module> if (int(grid[x][y]) > int(grid[x-1][y]) and int(grid[x][y]) > int(grid[x+1][y]) and int(grid[x][y]) > int(grid[x][y+1]) and int(grid[x][y] > int(grid[x][y-1]))): ValueError: invalid literal for int() with base 10: 'X' 语句中的字符串上应用int函数,但我想不出为什么同样适用于此:

http://www.martinkysel.com/hackerrank-cavity-map-solution/

上述网站还显示了对列表值应用的if函数。如果有更好的代码可以完成任务,请告诉我们。

1 个答案:

答案 0 :(得分:1)

应该这样做..

n = int(raw_input().strip())
grid = []
for grid_i in xrange(n):
    grid+= raw_input().split()

a=[grid[0]]
for x in xrange(1, n-1):
    s=''
    s+=grid[x][0]
    for y in xrange(1, n-1):        
        if(int(grid[x][y]) > int(grid[x-1][y]) and int(grid[x][y]) > int(grid[x+1][y]) and int(grid[x][y]) > int(grid[x][y+1]) and int(grid[x][y] > int(grid[x][y-1]))):
            s+= "X"
        else:
            s+=grid[x][y]
    s+=grid[x][n-1]    
    a.append(s)
a.append(grid[n-1])

print a