3 回答
TA贡献1848条经验 获得超6个赞
没有 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 tuple
if __name__ == '__main__':
print(odds_evens([1,2,3]))
TA贡献1856条经验 获得超11个赞
只需要计算偶数(或奇数)。
def odds_evens(lista):
even = 0
for i in lista:
if i%2==0:
even += 1
return (even, len(lista) - even)
添加回答
举报