因此该函数输入一个列表和一个数字。然后它应该返回该数字能够除以的列表的索引。如果列表中没有可以除以的数字,那么它应该只返回一个空白列表。
例如,
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/