Python 如何初始化空列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4001652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize empty list?
提问by Zeynel
Every time the input scomes from the form; the listis initialized again. How do I change the code to append each new sto the list?
每次输入s来自表单;在list重新初始化。如何更改代码以将每个新添加s到列表中?
Thank you.
谢谢你。
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
list = []
list.append(s)
htmlcode1 = HTML.table(list)
采纳答案by dln385
I'm not sure what the context of your code is, but this should work:
我不确定您的代码的上下文是什么,但这应该有效:
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
try:
self.myList.append(s)
except NameError:
self.myList= [s]
htmlcode1 = HTML.table(self.myList)
This makes listan instance variable so it'll stick around. The problem is that listmight not exist the first time we try to use it, so in this case we need to initialize it.
这会生成list一个实例变量,因此它会一直存在。问题是list在我们第一次尝试使用它时可能不存在,因此在这种情况下我们需要对其进行初始化。
Actually, looking at this post, this might be cleaner code:
实际上,看看这篇文章,这可能是更清晰的代码:
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
if not hasattr(self, 'myList'):
self.myList = []
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
[Edit:] The above isn't working for some reason, so try this:
[编辑:]以上由于某种原因不起作用,所以试试这个:
class Test(webapp.RequestHandler):
myList = []
def get(self):
s = self.request.get('sentence')
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
回答by sth
You could make the list a member variable of the object and then only update it when get()is called:
您可以使列表成为对象的成员变量,然后仅在get()调用时更新它:
class Test(webapp.RequestHandler):
def __init__(self, *p, **kw): # or whatever parameters this takes
webapp.RequestHandler.__init__(self, *p, **kw)
self.list = []
def get(self):
s = self.request.get('sentence')
self.list.append(s)
htmlcode1 = HTML.table(self.list)

