在Python中生成一个偶数列表 [英] Generating a list of EVEN numbers in Python
问题描述
基本上,我需要帮助从我在Python中创建的列表中生成偶数:
Basically I need help in generating even numbers from a list that I have created in Python:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...]
我尝试了几种不同的方法,但是每次打印时,偶数中都混有奇数!
I have tried a couple different methods, but every time I print, there are odd numbers mixed in with the evens!
我知道如何在0到100的范围内生成偶数/奇数,但是,我很难从前面提到的列表中获取偶数!
I know how to generate even/odd numbers if I were to do a range of 0-100, however, getting only the even numbers from the previous mentioned list has me stumped!
P.S.我只使用python几天,如果事实证明这非常简单,请提前感谢!
P.S. I've only been using python for a couple days, if this turns out to be extremely simple, thanks in advance!
感谢您的所有答复,在您的帮助下,我已经解决了这个小问题.这是我最后要完成的一些练习,要求对斐波那契数列的偶数求和:
Thanks for all the replies, with your help I've gotten through this little problem. Here is what I ended up with to complete a little excercise asking to sum the even numbers of fibonacci sequence:
F = [1, 2]
while F[-1] < 4000000
F.append(F[-1] + F[-2])
sum(F[1::3])
4613732
推荐答案
Use a list comprehension (see: Searching a list of objects in Python)
myList = [<your list>]
evensList = [x for x in myList if x % 2 == 0]
这很好,因为它使列表完整无缺,并且您可以将evensList用作普通列表对象.
This is good because it leaves list intact, and you can work with evensList as a normal list object.
希望这会有所帮助!
这篇关于在Python中生成一个偶数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!