2016-09-19 4 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

list comprehension를 사용하여 수행 할 수 있습니다 나는이 코드를 실행하면 내가 마사지를 얻을 수 무슨 일 이니?

# 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

당신은 또한 당신이 실제로 각 문장보고 확인하여 여기에 대한 답변에서 더 많은 것을 얻을 수 있습니다 생각

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

@ idjaw oops, 나는 잠시 동안 그것을 잘못 이름 짓고 있었음에 틀림 없어, 얼마나 당황 스럽 냐고 ... 나를 고쳐 주셔서 감사합니다. – Dunno