嵌套循环,返回列表只包含偶数整数

时间:2013-10-17 01:08:28

标签: python list nested-loops

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:

        even_lists = []

    for sublist in lst:

        for numb in sublist:
            if numb[i]%2 == 0:
                even_list.append(sublist)

    return even_lists

我收到此错误:NameError:未定义全局名称“i” 功能体有什么问题?

2 个答案:

答案 0 :(得分:1)

正如错误所说:i未定义。

您尝试在此处使用变量i

if numb[i]%2 == 0:
# here--^

但你从未定义过它。定义i以解决问题

答案 1 :(得分:1)

numb不是列表而是实际值,如果不重要,您可以选择删除索引:

if numb%2 == 0:

或者更改循环以在索引很重要时为您提供索引:

for i in range(len(sublist)-1):
    if sublist[i]%2 == 0:

但在这种情况下,我会使用枚举:

for i, numb in enumerate(sublist):
    if numb%2 == 0:

由于您只想添加包含所有evens的列表,因此您可能需要调查else循环的for子句:

for numb in sublist:
    if numb%2 != 0:
        break
else:
    even_list.append(sublist)