简体   繁体   English

打印新列表时,由于未定义新列表而出现错误

[英]When printing newlist getting error as newlist is not defined

def one(mylist):
    newlist=[]
    if len(mylist)>0:
        newlist.append(mylist[0])
    if len(mylist)>1:
        newlist.append(mylist[1])
    return newlist 

values = [35,40,50,38,20] 
print newlist
print one(newlist)
print newlist 

Its a small program that I am trying to run on python but getting error as newlist is not defined when printing new list. 它是一个小程序,我尝试在python上运行,但在打印新列表时未定义newlist的错误。 Why? 为什么?

newlist array is defined inside the one function and its scope is limited to that function so it is inaccessible outside the function. newlist数组是在一个函数内部定义的,其范围仅限于该函数,因此在函数外部无法访问。

def one(mylist):
  newlist=[]
  if len(mylist)>0:
    newlist.append(mylist[0])
  if len(mylist)>1:
    newlist.append(mylist[1])
  return newlist 

values = [35,40,50,38,20] 
print one(values) #This will give the value of newlist returned from the 
#function

Or you can use: 或者您可以使用:

newlist=one(values)
print newlist

Why your codes look so complex, it can be done in this way to avoid of judging the len(mylist) and initializing of newlist: 为什么您的代码看起来如此复杂,所以可以通过这种方式来避免判断len(mylist)和初始化newlist:

def one(mylist):
    newlist = mylist[0:2]
    return newlist


values = [35, 40, 50, 38, 20]

print(one(values))

The code above could handle the case when values is empty [ ] or has only one element; 上面的代码可以处理value为空[]或只有一个元素的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM