打印列表中直到给定数字的所有偶数
我刚开始接触Python,正在学习learnpython.org上的章节。在“循环”这一章,我用以下代码解决了一个挑战。不过,我不太确定这是不是最有效的做法。感觉上似乎不是,因为我需要定义“不能超过的数字”两次。在这个(我猜)简单的问题中,应该可以遵循DRY原则吧?
这个练习是:
遍历并打印出数字列表中的所有偶数,顺序和接收到的一样。不要打印出在序列中237之后的任何数字。
我的代码:
numbers = [ 951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527 ]
# My Solution
for x in numbers:
if x != 237:
if x % 2 == 0:
print x
if x == 237:
break
6 个回答
1
另一种方法是使用 itertools
,这个工具总是能以某种方式派上用场:
>>> from itertools import takewhile, ifilter
>>> not_237 = takewhile(lambda L: L != 237, numbers)
>>> is_even = ifilter(lambda L: L % 2 == 0, not_237)
>>> list(is_even)
[402, 984, 360, 408, 980, 544, 390, 984, 592, 236, 942, 386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918]
我们创建一个懒惰的迭代器,它会在237这个数字处停止,然后从中取出偶数。
1
这也是可以做到的:
try:
i = numbers.index(237)
except:
i = len(numbers)
for n in numbers[:i]:
if not n%2:
print n
2
这就是 else
和 elif
的作用:
for x in numbers:
if x == 237:
break
elif x % 2 == 0:
print x