2016-09-19 94 views
2
class targil4(object): 
    def plus(): 
     x=list(raw_input('enter 4 digit Num ')) 
     print x 
     for i in x: 
      int(x[i]) 
      x[i]+=1 
     print x 

    plus() 

這是我的代碼,我試着從用戶那裏得到4位數的輸入,然後給每個數字加1,然後打印回來。當我運行這段代碼我得到的按摩:列表索引必須是整數,而不是str

Traceback (most recent call last): 
['1', '2', '3', '4'] 
    File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 1, in <module> 
class targil4(object): 
    File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 10, in targil4 
    plus() 
    File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 6, plus 
    int(x[i]) 
TypeError: list indices must be integers, not str 

Process finished with exit code 1 
+1

'i'已經是您列表中的每個值。做x [i]'是不正確的使用打印循環中發生的事情來進一步理解,並在循環中重新訪問你的課程計劃。 – idjaw

回答

1

我相信你可以通過實際觀察每個語句,看到獲得更多的答案在這裏到底是怎麼回事。

# Because the user enters '1234', x is a list ['1', '2', '3', '4'], 
# each time the loop runs, i gets '1', '2', etc. 
for i in x: 
    # here, x[i] fails because your i value is a string. 
    # You cannot index an array via a string. 
    int(x[i]) 
    x[i]+=1 

所以我們可以通過我們的新理解來調整代碼來「修復」這個問題。

# We create a new output variable to hold what we will display to the user 
output = '' 
for i in x: 
    output += str(int(i) + 1) 
print(output) 
+1

@idjaw好的。這就是我匆忙寫作的原因。 :-) 謝謝! – Frito

+0

非常感謝!有效! –

0

您還可以使用list comprehension

y = [int(i) + 1 for i in x] 
print y 
+0

@idjaw哎呀,我一定是誤會了一會兒,好尷尬......謝謝你糾正我 – Dunno

相關問題