【发布时间】:2021-05-21 00:41:42
【问题描述】:
请帮助解决这个家庭作业...我尝试了不同的途径,但无法让索引错误消失...
# 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
【问题讨论】:
-
zip迭代元素本身,而不是它们的索引。for i in list1也是如此。i已经是列表的元素,而不是您必须用来获取元素的索引。