nums = [1,2,3,4,5,6,7,8,9,10,11,12]
odds = [ n for n in nums if n%2 ]
print odds
给出:
>>>
[1, 3, 5, 7, 9, 11]
这可以放入这样的函数中:
def getOdds(aList):
return [ n for n in aList if n%2 ]
示例用法:
myOdds = getOdds(nums)
print("{0} has {1} odd numbers which were {2}".format(nums,len(myOdds),myOdds))
print("The odd numbers sum to {0}".format(sum(myOdds)))
产生:
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] has 6 odd numbers which were [1, 3, 5, 7, 9, 11]
The odd numbers sum to 36
至于你做错了什么,你正在迭代一个包含元素的可迭代对象0
,size
这并不总是num
(除非num
确实是)的值range(size)
。一旦你i
表示一个num
你正在迭代的值,if i%2 == 0
将意味着它是偶数,如果你想要赔率,这个数字不能被 2 整除。因此,这应该更改为if i%2 != 0
or 或if i%2
。您还必须在循环之前odd
声明列表,以便您可以在选择控制结构中附加满足条件的数字。您应该通过执行添加号码for i ...
num
if i%2
num
odd.append(i)
,此时您正在重新分配奇数一个新值。你也不应该增加i
. 'i' 应该代表一个数字而num
不是数字的索引num
。