0

Hey guys I'm trying to make a program that counts the evens in a two-dimensional list. The program I made so far is not returning what I want it to.

def Evens(x):
    count = 0
    x = len(x)
    for a in range(x):
        if a%2 == 0:
            count = count + 1
    return count

that keeps returning 2 for the list Evens([[1,3],[1,9,7,1,3],[13]]) when I want it to return 4. I tried everything but it seems to not be working correctly.

Thanks

4

4 回答 4

3

您遇到的问题是您正在检查索引以查看它们是否是偶数,而不是值。您也没有检查子列表。

IMO 更直接的是这样做:

import itertools
def evens(x):
    return sum(a % 2 == 0 for a in itertools.chain.from_iterable(x))
于 2013-02-11T08:04:26.347 回答
3

您需要实际迭代子列表。

def evens(l):
    count = 0
    for l2 in l:
        for i in l2:
            if i%2 == 0:
                count += 1
    return count

或者你可以采取更简单的方法。

def evens(l):
    return sum(i%2==0 for l2 in l for i in l2)

第二种方法使用的事实是,在整数上下文中,True == 1False == 0,所以你会得到预期的结果。

于 2013-02-11T08:05:42.773 回答
2

您需要遍历所有子列表:

In [34]: l = [[1,4,3],[12,0,7,10,3],[13]]

In [35]: sum(n%2 == 0 for sub in l for n in sub)
Out[35]: 4
于 2013-02-11T08:04:53.380 回答
0

您还需要遍历每个子列表中的元素:

def count_evens(l):
    total = 0

    for l2 in l:
        for item in l2:
            if item % 2 == 0:
                total += 1

    return total

您之前所做的是迭代子列表的数量(即[0, 1, 2, 3]对于包含4元素的列表)。您的代码工作正常,但工作不正常。

于 2013-02-11T08:04:36.930 回答