-5
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',函数体有什么问题?

4

2 回答 2

1

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

您尝试在i此处使用变量:

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

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

于 2013-10-17T01:09:53.293 回答
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:

当您只想添加包含所有偶数的列表时,您可能需要研究循环的else子句:for

for numb in sublist:
    if numb%2 != 0:
        break
else:
    even_list.append(sublist)
于 2013-10-17T01:16:23.813 回答