并行迭代列表。。帮助

2024-10-03 04:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮我解决这个家庭作业。。。我尝试了不同的方法,只是无法消除索引错误

# 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


Tags: theinfromnonenumbernew错误list
2条回答

这个问题特别要求理解一个函数和一个列表。以下是您的操作方法:

testlist1 = [-1, 0, 2, 178, -17.2, 12, -2, -3, 12]
testlist2 = [0, 5, 0, 2, 12, 0.5, 0, 0.25, 0]

def divide(num1, num2):
    if num2 != 0:
        return num1/num2
    else:
        return None

result = [divide(x,y) for x, y in zip(testlist1, testlist2)]
print(result)

#output:
[None, 0.0, None, 89.0, -1.4333333333333333, 24.0, None, -12.0, None]

似乎这个问题要求你使用列表理解。你可以试试这个

new_list= [[x/ y] if y!=0 else None for x,y in zip(testlist1,testlist2)]

或者要使用函数,可以使用Lambda函数

new_list2= [(lambda x,y: x/y )(x,y)if y!=0 else None for x,y in zip(testlist1,testlist2) ]

相关问题 更多 >