如何在python中创建不需要声明的变量



我可以让python在飞行中创建变量,假设最合理的文件类型?

换句话说,如何避免创建空变量?在这个循环中,i似乎不需要介绍,为什么list需要介绍呢?

list=[]
for i in other_list:
     list.append(i)

在这种情况下,您需要添加一些内容。既然你在修改一些已经存在的东西,那么这个东西就需要存在。i未被修改

Python实际上允许你在没有先前实例化的情况下内联列表,它被称为list comprehension,它的工作原理是这样的:

dont_name_your_variables_list = [i*2 for i in range(10)]

编辑:另一种思考这一点的方式,正如@BrenBarn所提到的,将其视为无法对尚未分配值的变量做任何事情。

第一个解释:

i+1  # i does not yet exist, and since i+1 is a modification on i, this will not work

第二种解释:

i+1  # i has no value assign to it. Since i+1 is doing something to i, this will not work.

for循环 item的声明/引入。你不必声明变量,但是每个变量都必须有一个值。你不能创建一个没有值的变量,也不能使用一个没有值的变量。

赋值的一种方法是执行someVar = blah。另一种方法是执行for someVar in blah——也就是说,for循环将值赋给变量,就像=赋值一样。Python中还有其他结构可以为变量赋值,例如defclass

listitem都有在代码中分配给它们的值,只是以不同的方式。你不能做的是对一个没有赋值的变量做一些事情。

必须显式地创建list,否则Python将不知道它应该具有什么值。i的创建被允许更加隐式,因为i的值是由您正在循环的列表自动确定的。

据我所知,这是语法糖。

for i in list:
list.append(item)

被解释为(在伪代码中)

Create variable i
Set type of i to type of the first entry in list
While the list is not scanned through completely:
    Append item to the list.

最新更新