python - 如何获取给定数字的约数列表?

标签 python

因此该函数输入一个列表和一个数字。然后它应该返回该数字能够除以的列表的索引。如果列表中没有可以除以的数字,那么它应该只返回一个空白列表。

例如,

div([5,10,15,2,34],10)
[0,1,3]

这是我的编码:

def div(nlst, n):
    nlst = []
    for div in nlst:
        if n % nlst == 0:
        return nlst.index(div)
        else: []

我的代码有什么问题吗?

最佳答案

您的代码中存在一些问题:

def div(nlst, n):
    nlst = [] # You are deleting the original list here!
    for div in nlst: # The list nlst is empty
        if n % nlst == 0: # Cannot use a list 'nlst' as an operand of the % operation.
        return nlst.index(div) # You are returning a single element here
        else: [] # This does nothing

这段代码可以完成这项工作:

def div(nlst, n):
    result = []
    for i, e in enumerate(nlst):
        if n % e == 0:
            result.append(i)
    return result

更紧凑的版本:

def div(nlst, n):
    return [i for i, e in enumerate(nlst) if n % e == 0]

关于python - 如何获取给定数字的约数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4988301/

相关文章:

python使用正则表达式根据前一行读取接下来的n行

python - Tensorflow 使用上一次迭代的值计算指标的 update_op

python - Keras 批量训练回调串联

python - 将文件中的所有行转换为小写然后写入新文件

python - 将 numpy.array 传递给 ctypes 但得到错误结果的问题

python - 错误 : "make: * [Makefile:163: all] Error 2" and "make: * [Makefile:163: all] Interrupt"

python - 如何在 Python 中打印不带括号的元组列表

python - 文件中的通用字符串替换

python - 简化 numpy argmin 的愚蠢循环

python - argparse 与 argument_groups 和 mutually_exclusive_group