简体   繁体   English

如何为 python 3 创建一个空列表?

[英]How create a empty list to python 3?

What is the problem in this code, because I need create a empty list and I can't create a empty list.这段代码有什么问题,因为我需要创建一个空列表而我无法创建一个空列表。

def empty_list():
    empty_list=[]
    return empty_list
def text_to_list(the_text):
    empty_list=empty_list()
    empty_list[:0]=the_text
    return empty_list
# The print to show the result.
print(text_to_list("ABCD"))

The result:结果:

Traceback (most recent call last):
  File "./prog.py", line 9, in <module>
  File "./prog.py", line 5, in text_to_list
UnboundLocalError: local variable 'empty_list' referenced before assignment

Simply简单地

empty_list = []

will create an empty list that you can add to and call on将创建一个空列表,您可以添加并调用它

The issue is caused by the shared name between the variable and the function.该问题是由变量和 function 之间的共享名称引起的。 Python checks for the variables created in the function before the function gets executed. Python 在执行 function 之前检查在 function 中创建的变量。 At the time of the call, the interpreter already considers the empty_list a variable.在调用时,解释器已经将empty_list一个变量。

Solution Rename the function or the variable.解决方案重命名 function 或变量。

You don't really need functions to do this, but if you want to work with your code, make sure you don't use the same names for functions and variables.您实际上并不需要函数来执行此操作,但如果您想使用您的代码,请确保不要为函数和变量使用相同的名称。 In your code, empty_list is used for almost everything which is confusing.在您的代码中, empty_list用于几乎所有令人困惑的事情。

def empty_list():
    a_list=[]
    return a_list

def text_to_list(the_text):
    another_list = empty_list()
    another_list[:0] = the_text
    return another_list

# The print to show the result.
print(text_to_list("ABCD"))

As an aside, you can accomplish all of the above in one line as Python can easily convert strings to lists like so:顺便说一句,您可以在一行中完成上述所有操作,因为 Python 可以轻松地将字符串转换为列表,如下所示:

>>> list("ABCD")
['A', 'B', 'C', 'D']

A possible solution is calling the list() constructor, using it in a code would look something along the lines of一个可能的解决方案是调用 list() 构造函数,在代码中使用它看起来类似于

empty_list = list()

That will create an empty list.这将创建一个空列表。

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

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