2016-03-12 116 views
-1

我正在寫一些代碼以'X'替換大於相鄰值(上,下,左和右)的方陣中的所有值。但是當我嘗試執行它時,我收到了一個ValueError錯誤。替換Python中的列表中的值

這裏是我的代碼:

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' 

我的理解是錯誤意味着我嘗試應用上的if語句的字符串的int功能,但我想不出爲什麼這裏同樣適用:

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

上面的網站還顯示了int函數被應用於列表值。如果有更好的代碼可以完成這個任務,請告訴我們。

+1

因爲他有'ARR [idx_tb-1] [idx_lr]!= 'X' 和'開頭。 – zondo

+0

對於raw.input()。strip()。split()]中的'grid_t = [int(i)',它允許您在下面放下四個嘈雜且重複的int整數轉換。 – msw

+0

@zondo - 是的,我看到了,但我不明白它有什麼好處 –

回答

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