【问题标题】:Iterating lists in parallel.. assistance并行迭代列表..帮助
【发布时间】: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 已经是列表的元素,而不是您必须用来获取元素的索引。

标签: python list iteration


【解决方案1】:

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

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) ]

【讨论】:

    【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 2010-10-24
      • 2013-11-14
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多