繁体   English   中英

将python函数的结果保存到列表中

[英]Save results of a python function into a list

大家下午好 - 我遇到了一个问题,这是一个简单的问题,但是我在 base python (3.7) 中遇到了一些问题 问题:所以我正在尝试创建这个循环,它只是找到一个整数的除数和然后我想将结果保存为可索引的对象(例如列表)但是当我运行以下代码时,我标记为“test”的对象是一个空列表

# function divisors
def divisors(n):
#empty list start
    test = []
    i = 1
    while i <= n:
        if (n % i == 0):
        print(i),
        #append test
        test.append(i), # I know i is not the correct object here, it's just a place holder for this example
    i = i + 1

你能指出我在这里犯了什么错误吗? 我可以使用 numpy 解决这个问题,但我想了解 python 以及它如何更好地工作。 似乎我必须添加一个变量来存储循环的结果,然后用该变量追加测试?

非常感谢

您可以将列表作为参数传递:

def divisors(test):
    i = 1
    while i <= n:
        if (n % i == 0):
            print(i)
        #append in test
        test.append(i), # I know i is not the correct object here, it's just a place holder for this example
        i = i + 1

a = []
divisors(a)

或返回您的列表:

def divisors():
    test = []
    i = 1
    while i <= n:
        if (n % i == 0):
            print(i)
        #append in test
        test.append(i), # I know i is not the correct object here, it's just a place holder for this example
        i = i + 1
    return test

a = divisors()

暂无
暂无

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

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