-1

这是代码:

aList = []
for p in anotherList:
  aList.append(p)
  try:
    k=p.someMethod()
    aList.append(k) #getting error here
  except someException:
    continue
 return aList

我收到“全局名称错误--aList 未定义。为什么会这样?

4

2 回答 2

1

如果aList未定义,您应该在进入 try-except 子句aList.append(p)之前在循环顶部收到错误。aList.append(k)你确定你没有错别字?

aList = []
for p in anotherList:
  aList.append(p) # <== should have gotten error here first!
  try:
    k=p.someMethod()
    aList.append(k) #getting error here
  except someException:
    continue
 return aList
于 2012-12-05T19:48:46.153 回答
0

这段代码没有任何问题。

>>> anotherList = [1, 2, 3, 4, 5]
>>> aList = []
>>> for p in anotherList:
...     aList.append(p)
...     try:
...             aList.append(9)
...     except someException:
...             continue
... 
>>> aList
[1, 9, 2, 9, 3, 9, 4, 9, 5, 9]

如您所见,它有效。

如果您仍然有问题,请发布更多代码,您发布的部分没有错误。

于 2012-12-05T19:46:04.830 回答