Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

python - Even numbers a list?

How do I create a list and only extract or search out the even numbers in that list?

Create a function even_only(l) that takes a list of integers as its only argument. The function will return a new list containing all (and only) the elements of l which are evenly divisible by 2. The original list l shall remain unchanged.

For examples, even_only([1, 3, 6, 10, 15, 21, 28]) should return [6, 10, 28], and even_only([1, 4, 9, 16, 25]) should return [4, 16].

Hint: Start by creating an empty list, and whenever you encounter an even number in it, add it to your list, then at the end, return your list.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"By hand":

def even_only(lst):
    evens = []
    for number in lst:
        if is_even(number):
            evens.append(number)
    return evens

Pythonic:

def even_only(iter):
    return [x for x in iter if is_even(x)]

Since it's homework, you can fill in the is_even function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...