请考虑以下代码

时间:2017-11-14 09:49:31

标签: python python-2.7

import sys
n = input()
a = []
for i in range(n):
    temp = input()
    a[i].append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] ==0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]

代码运行时没有任何错误,但在输入

后出错
2
2 2
Traceback (most recent call last):
  File "1.py", line 5, in ?
    temp = input()
  File "<string>", line 1
    2 2
     ^
SyntaxError: unexpected EOF while parsing

为什么它不起作用并给出EOF错误?

2 个答案:

答案 0 :(得分:0)

a[i]不起作用,因为列表a只是一个数组。如果数组中包含列表,则a[i]将起作用。

只要数组中有足够的列表允许for循环运行。

因此,在运行第一个for循环之前,需要将n数组([])追加到a

答案 1 :(得分:0)

我认为你必须从[i] .append(temp)

中删除[i]
import sys
n = input('Please input n: ')
a = []
for i in range(n):
    temp = input('Please input temp: ')
    a.append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] == 0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]

结果是:

Please input n: 5
Please input temp: 1
Please input temp: 2
Please input temp: 3
Please input temp: 4
Please input temp: 5
NO
YES
0
2
3
4
5

如果我理解你的任务。