如何获得给定数字的除数列表?

时间:2011-02-14 02:18:42

标签: 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: []

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

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

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]

答案 1 :(得分:1)

列出对救援的理解:

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

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