繁体   English   中英

在列表中查找 integer 的可除数

[英]Finding the divisables of an integer in a list

大家好,我刚刚开始编写代码,我正在尝试解决以下问题:下面的 function 应该接受两个 arguments、一个 integer 和一个整数列表

function 应该为列表中的所有整数返回一个 True 和 False 的列表,其中第一个参数可被整除,否则返回 False。

例如,function 调用:

main(10, [12, 2, 22, 5 ]) 

应该return [False, True, False, True]

这是我的代码:

def main(integer_1, list_1):
    result= “
    for element in list_1:
        if integer_1%element==0:
            result += "True"
        else:
            result += "False"

print(main(10, [12, 2, 22, 5 ]))

但是它返回None

您必须返回结果,最好使用列表而不是字符串。 初始化它:

your_list = []

然后调用:

your_list.append(new_element)

在这种情况下,new_element 是 True of False 最后:

return your_list

您应该在 function 的末尾return结果,如下所示:

def main(integer_1, list_1):
    result = ''
    for element in list_1:
        if integer_1 % element == 0:
            result += "True"
        else:
            result += "False"
    return result

如果您执行代码的 rest,这将为您提供:

FalseTrueFalseTrue

所以你可能想在“True”和“False”的字符串表示的末尾添加一个空格,这将在最后给你这个 output:

False True False True

暂无
暂无

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

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