【问题标题】:Python - return the list of lists in lst that contain only integers?Python - 返回 lst 中仅包含整数的列表列表?
【发布时间】:2014-02-19 05:21:12
【问题描述】:
def only_evens(lst):
    """
    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 = []
    condition = True 

    for sublist in lst:
        for num in sublist: 
            if num % 2 != 0: 
                condition = condition and False
        if condition == True: 
            even_lists.append(sublist)

    return even_lists

我不明白为什么这总是返回一个空字符串?直觉上,这有意义吗?非常感谢您的帮助。我被困在这件事上太久了。

编辑:非常感谢大家!我现在明白了:)。

【问题讨论】:

    标签: python list for-loop nested-forms nested-loops


    【解决方案1】:

    您正在循环外初始化condition。这应该为每个子列表重新初始化,condition = condition and False 将始终评估为False,应该是condition = False

    for sublist in lst:
        condition = True
        for num in sublist: 
            if num % 2 != 0: 
                condition = False
                break
    

    这可以通过all函数来完成,像这样

    return [sublist for sublist in lst if all(item % 2 == 0 for item in sublist)]
    

    示例运行

    def only_evens(lst):
        return [sublist for sublist in lst if all(item % 2 == 0 for item in sublist)]
    
    print only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    # [[4, 0, 6], [2]]
    

    【讨论】:

      【解决方案2】:

      thefourtheye 已回答您的问题。但是使用它,它会“更简单”:

      [sublst for sublst in lst if all(x%2 == 0 for x in sublst)]
      

      【讨论】:

        【解决方案3】:

        问题是condition and False

        在 python 提示符下:

        >>> True and False
        False
        >>> False and False
        False
        

        我还重新编写了代码以使用 yield 语句和 for..else 循环控制魔法,只是为了好玩:

        def only_evens(lst):
            for sub_lst in lst:
                for num in sub_lst:
                    if num % 2 != 0:
                        break
                else:
                    yield sub_lst
        
        print list(only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]]))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多