odds_evens(lista) = [odd,even odd+=1 if lista[i]%2==0 else even+=1 for i in range[0,len(lista)]]
我究竟做错了什么?
我期待odds_evens([1,2,3])给出答案(2,1)
桃花长相依
浏览 212回答 3
3回答
慕勒3428872
没有 for 循环的解决方案:def odds_evens(lista): return (sum(num%2 == 1 for num in lista), sum(num%2 == 0 for num in lista))if __name__ == '__main__': print(odds_evens([1,2,3]))如果你真的需要使用 for 循环,这里有一种方法:def odds_evens(lista): odd = 0, even = 0 # Variable Initialization for i in range(0, len(lista)): # You did range[]. range is a method - range() if lista[i]%2==0: even+=1 else: odd+=1 return (odd, even) # Returns a tupleif __name__ == '__main__': print(odds_evens([1,2,3]))
只需要计算偶数(或奇数)。def odds_evens(lista): even = 0 for i in lista: if i%2==0: even += 1 return (even, len(lista) - even)