Python 如何获得给定数字的除数列表?
因此,函数输入一个列表和一个数字。然后它应该返回列表的索引,该数字可以除以该索引。如果列表中没有可以除以的数字,那么它应该只返回一个空白列表 比如说,Python 如何获得给定数字的除数列表?,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: [] 我的代码有什
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]
列出对救援的理解:
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]
我做错的编码是什么?