为什么这个特定的函数返回“ none”;我想证明一个不断增加的清单?

时间:2018-11-28 04:27:53

标签: python-3.x list function loops append

我想实时查看列表,完成后我想通过索引查询附加列表。

l=[]
def GrowingList(list):
    try:
        import random
        while True:
            rlist=lambda: print([random.randint(0,12)])
            list.append(rlist())
            print(list)
        return GrowingList(list)

    except KeyboardInterrupt:
        pass

这是笔录:

Grown list
[None]
Grown list
[None, None]
Grown list
[None, None, None]
Grown list
[None, None, None, None]

当我查询新的已编译列表时,它为每个索引显示“ none”:

>>> l
[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

我是编程新手,所以请放心。此列表只是如何自动增长列表的练习功能。 “成长列表”只是我想放入列表中的一个示例。

1 个答案:

答案 0 :(得分:0)

您正在lambda中使用print,它将返回None。同样,您的退货没有必要进行递归。

edit:您可以删除完整的lambda部分,然后将随机值直接附加到列表中。

您可以使用以下修改后的代码:

import random
l=[]
count=1
def GrowingList(list):
    try:
        count=1

        while True:
            rlist=random.randint(0,12)
            list.append(rlist)
            print(list)
            #below three line is added to break the code after 10 iteration you can remove them if you want to break on keyboard interrupt.  
            count+=1
            if count > 10:
                break
        return list

    except KeyboardInterrupt:
        pass

输出:

[1, 10]
[1, 10, 8]
[1, 10, 8, 11]
[1, 10, 8, 11, 2]
[1, 10, 8, 11, 2, 10]
[1, 10, 8, 11, 2, 10, 12]
[1, 10, 8, 11, 2, 10, 12, 5]
[1, 10, 8, 11, 2, 10, 12, 5, 0]
[1, 10, 8, 11, 2, 10, 12, 5, 0, 8]
[1, 10, 8, 11, 2, 10, 12, 5, 0, 8, 8]