简体   繁体   English

如何使用 python 中的 function 连续扩展列表?

[英]How to extend a list continuously with a function in python?

as the title says I have the problem that I can't do a function, where the list is expanding continuously to some value.正如标题所说,我有一个问题,我不能做一个 function,其中列表不断扩大到某个值。 I need this for a bigger program I'm writing.我需要这个来编写一个更大的程序。

Here are two examples that don't work.这是两个不起作用的示例。 first one:第一:

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)

and second one:第二个:

from random import *
import time


def list_expander():
    A = []
    A = A + [randint(-5,5)]
    print (A)

while True:
    list_expander()
    time.sleep(2)

thank you for your help!谢谢您的帮助!

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)


To modify an immutable item (for example a list ), you can use its mutating methods ( .append() in this case).要修改不可变项(例如list ),您可以使用其变异方法(在本例中为.append() )。 So in your first example if you replace A = A + [randint(-5,5)] with A.append(randint(-5, 5)) , you should get what you want.所以在你的第一个例子中,如果你用A.append(randint(-5, 5))替换A = A + [randint(-5,5)] ,你应该得到你想要的。 Your first example does not work because the function creates a "new" A every time you call it, it does not "change" the outside list A .您的第一个示例不起作用,因为 function 每次调用它时都会创建一个“新” A ,它不会“更改”外部列表A The second one obviously won't work either because of the same reason, and also the fact that it reinitialises A with an empty list every time it's called ( A = [] ).由于同样的原因,第二个显然也不起作用,而且它每次调用时都会用一个空列表重新初始化AA = [] )。

All in all, I would rewrite your code as:总而言之,我会将您的代码重写为:

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)

You can read How do I pass a variable by reference?您可以阅读如何通过引用传递变量? to better understand why your first example doesn't change the list A .为了更好地理解为什么您的第一个示例不会更改列表A

As far as I understand you want to keep appending to the list, so you will have to return it so that you can append to it (extend) again next iteration.据我了解,您希望继续附加到列表中,因此您必须将其返回,以便在下一次迭代中再次将 append 再次添加到它(扩展)。

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

This code will print此代码将打印

[1]
[1, -5]
[1, -5, 4]
[1, -5, 4, 5]
[1, -5, 4, 5, 2]

Another approach you can take is to have the list as a global variable but keep in mind it's bard practice.您可以采取的另一种方法是将列表作为全局变量,但请记住这是吟游诗人的做法。

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

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