如标题所述,我有一个我无法执行功能的问题,该列表不断扩展到某个值。我需要这个来编写更大的程序。
以下是两个不起作用的示例。第一个:
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)
据我了解,您希望继续追加到列表,因此必须返回它,以便您可以在下一次迭代时再次将其追加(扩展)。
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)
x+=1
将打印此代码
[1]
[1, -5]
[1, -5, 4]
[1, -5, 4, 5]
[1, -5, 4, 5, 2]
[您可以采用的另一种方法是将列表作为全局变量,但请记住,这是常规做法。