简体   繁体   English

如何从列表中仅获取偶数

[英]How to get only even numbers from list

def only_evens(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers. 

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """

    even_lists = []

    for sublist in lst:
        for i in sublist:
            if i % 2 == 0:
                even_lists.append(i)
    return even_lists

I can't do this because it returns everything in one list[] But how can I return sublist that consists only with even integers? 我无法执行此操作,因为它会返回一个列表中的所有内容[]但是如何返回仅包含偶数整数的子列表?

I would split it into two functions: one which checks if a list contains only even numbers, and the other one is your main function (I renamed it to get_even_lists() ), which gets all the even lists from a list of lists: 我将其分为两个函数:一个检查列表是否仅包含偶数,另一个函数是您的主要函数(我将其重命名为get_even_lists() ),该函数从列表中获取所有偶数列表:

def only_even_elements(l):
    """ (list of int) -> bool

    Return a whether a list contains only even integers.

    >>> only_even_elements([1, 2, 4])  # 1 is not even
    False
    """
    for e in l:
        if e % 2 == 1:
            return False
    return True

def get_even_lists(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers. 

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """
    # return [l for l in lst if only_even_elements(l)]
    even_lists = []
    for sublist in lst:
        if only_even_elements(sublist):
            even_lists.append(sublist)
    return even_lists

Although, this could be done with for / else : 虽然,这可以通过for / else

def get_even_lists(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers. 

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """
    even_lists = []
    for sublist in lst:
        for i in sublist:
            if i % 2 == 1:
                break
        else:
            even_lists.append(sublist)
    return even_lists

Or as others have suggested, a one-liner: 或者像其他人所建议的那样,采用单线:

def get_even_lists(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers. 

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """
    return [sublst for sublst in lst if all(i % 2 == 0 for i in sublst)]

But let's be honest here: while it's arguable that using two functions might be a bit longer and not as "cool" as the other two solutions, it's reusable, easy to read and understand, and it's maintainable. 但是,在这里说实话:虽然使用两个函数可能会更长一些,并且不如其他两个解决方案那么“酷”,但这是可重用的,易于阅读和理解,并且可维护。 I'd argue it's much better than any other option out there. 我认为这比那里的其他选择要好得多。

You could also do this using functional programming: 您也可以使用函数式编程来做到这一点:

def only_evens(lst):
    return filter(lambda ls: all(map(lambda n: not n & 1, ls)), lst)

EDIT 编辑

As per JF Sebastian's recommendation, I split this into three functions: 根据JF Sebastian的建议,我将其分为三个功能:

is_odd = lambda n: n & 1
all_even = lambda arr: not any(map(is_odd, arr))
only_evens = lambda arr: filter(all_even, arr)

is_odd one checks if a number is odd using bitwise operations for efficiency. is_odd使用位运算来检查数字是否为奇数以提高效率。 all_even checks if a list has all even numbers and returns a boolean. all_even检查列表是否具有所有偶数,并返回布尔值。 only_evens takes a list of list of integers and returns a list of the lists that contain only even integers. only_evens接受一个整数列表的列表,并返回仅包含偶数整数的列表的列表。

I would think not about what you are keeping, but about what you're removing (all lists containing an odd number). 我不会考虑保留的内容,而是考虑删除的内容(所有列表均包含奇数)。 Something like 就像是

import copy

list_copy = copy.copy(lists)
def only_evens(list_copy):
    for l in list_copy:
        for i in l:
            if i % 2 != 0:
                list_copy.remove(l)
                break
    return(list_copy) 

(which emphasizes readability over conciseness, to be sure.) (可以肯定的是,它强调可读性而非简洁性。)

I guess you can divide your problem into small parts. 我想您可以将问题分为几部分。

def contains_only_evens(lst):
    return sum([x%2 for x in lst]) == 0

def only_evens(lst):
    for sublist in lst:
        if not contains_only_evens(sublist):
            lst.remove(sublist)
    return lst

In this way you can: 这样,您可以:

  • iterate over a list and its sublists 遍历列表及其子列表
  • check if the list contains any odd integer 检查列表中是否包含任何奇数整数
  • keep only sublist with no odds values 只保留没有赔率值的子列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM