如何使用 python 中的函数连续扩展列表?
How to extend a list continuously with a function in python?
正如标题所说,我有一个问题,我无法执行列表不断扩展到某个值的功能。我需要这个用于我正在编写的更大的程序。
这里有两个不起作用的例子。
第一个:
from random import *
import time
A = []
def list_expander(A):
A = A + [randint(-5,5)]
print (A)
while True:
list_expander(A)
time.sleep(2)
第二个:
from random import *
import time
def list_expander():
A = []
A = A + [randint(-5,5)]
print (A)
while True:
list_expander()
time.sleep(2)
感谢您的帮助!
from random import *
import time
def list_expander(A):
A.append(randint(-5,5))
print (A)
return A
A=[]
while True:
A=list_expander(A)
time.sleep(2)
据我了解,您想继续追加到列表中,因此您必须 return 它以便下次迭代可以再次追加(扩展)它。
from random import *
import time
def list_expander(A):
A.append(randint(-5,5))
print (A)
A = []
while True:
list_expander(A)
time.sleep(2)
x+=1
此代码将打印
[1]
[1, -5]
[1, -5, 4]
[1, -5, 4, 5]
[1, -5, 4, 5, 2]
您可以采用的另一种方法是将列表作为全局变量,但请记住这是吟游诗人的做法。
要修改不可变项(例如 list
),您可以使用其变异方法(在本例中为 .append()
)。所以在你的第一个例子中,如果你用 A.append(randint(-5, 5))
替换 A = A + [randint(-5,5)]
,你应该得到你想要的。您的第一个示例不起作用,因为该函数在您每次调用它时都会创建一个 "new" A
,它不会 "change" 外部列表 A
。由于同样的原因,第二个显然也不起作用,而且每次调用时它都会用空列表重新初始化 A
(A = []
).
总而言之,我会将您的代码重写为:
from random import randint
from time import sleep
A = []
def list_expander(A):
A.append(randint(-5,5))
print(A) # are you sure you need this?
while True:
list_expander(A)
time.sleep(2)
您可以阅读 How do I pass a variable by reference? 以更好地理解为什么您的第一个示例没有更改列表 A
。
正如标题所说,我有一个问题,我无法执行列表不断扩展到某个值的功能。我需要这个用于我正在编写的更大的程序。
这里有两个不起作用的例子。 第一个:
from random import *
import time
A = []
def list_expander(A):
A = A + [randint(-5,5)]
print (A)
while True:
list_expander(A)
time.sleep(2)
第二个:
from random import *
import time
def list_expander():
A = []
A = A + [randint(-5,5)]
print (A)
while True:
list_expander()
time.sleep(2)
感谢您的帮助!
from random import *
import time
def list_expander(A):
A.append(randint(-5,5))
print (A)
return A
A=[]
while True:
A=list_expander(A)
time.sleep(2)
据我了解,您想继续追加到列表中,因此您必须 return 它以便下次迭代可以再次追加(扩展)它。
from random import *
import time
def list_expander(A):
A.append(randint(-5,5))
print (A)
A = []
while True:
list_expander(A)
time.sleep(2)
x+=1
此代码将打印
[1]
[1, -5]
[1, -5, 4]
[1, -5, 4, 5]
[1, -5, 4, 5, 2]
您可以采用的另一种方法是将列表作为全局变量,但请记住这是吟游诗人的做法。
要修改不可变项(例如 list
),您可以使用其变异方法(在本例中为 .append()
)。所以在你的第一个例子中,如果你用 A.append(randint(-5, 5))
替换 A = A + [randint(-5,5)]
,你应该得到你想要的。您的第一个示例不起作用,因为该函数在您每次调用它时都会创建一个 "new" A
,它不会 "change" 外部列表 A
。由于同样的原因,第二个显然也不起作用,而且每次调用时它都会用空列表重新初始化 A
(A = []
).
总而言之,我会将您的代码重写为:
from random import randint
from time import sleep
A = []
def list_expander(A):
A.append(randint(-5,5))
print(A) # are you sure you need this?
while True:
list_expander(A)
time.sleep(2)
您可以阅读 How do I pass a variable by reference? 以更好地理解为什么您的第一个示例没有更改列表 A
。