请帮我解决这个家庭作业。。。我尝试了不同的方法,只是无法消除索引错误
# Exercise 5: Using a function and a list comprehension, create a new list that includes the result
# from dividing each number from testlist1 by the corresponding number in testlist2;
# For the cases when the divisor is 0, the new list should include None
testlist1 = [-1, 0, 2, 178, -17.2, 12, -2, -3, 12]
testlist2 = [0, 5, 0, 2, 12, 0.5, 0, 0.25, 0]
def divLists(list1,list2):
newlist = []
for x,y in zip(list1,list2):
if list2[y] == 0:
q = None
newlist.append(q)
else:
q = list1[x]/list2[y]
newlist.append(q)
return newlist
print(divLists(testlist1,testlist2))
## i cant tell why this will not work i tried it this way as well.. it doesnt make sense to me why the list index is out of range
'''
def divLists(list1,list2):
newlist = []
for i in list1:
if list2[i] == 0:
q = None
newlist.append(q)
else:
q = list1[i]/list2[i]
newlist.append(q)
return newlist
print(divLists(testlist1,testlist2))
'''
任一解决方案都会出现以下错误: Error msg
这个问题特别要求理解一个函数和一个列表。以下是您的操作方法:
似乎这个问题要求你使用列表理解。你可以试试这个
或者要使用函数,可以使用Lambda函数
相关问题 更多 >
编程相关推荐