简体   繁体   中英

Counting evens in a two-dimensional list?

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

The problem you're encountering is that you are checking the indices to see if they are even, not the values. You're also not checking in the sublists.

More straightforward, IMO, is to do this:

import itertools
def evens(x):
    return sum(a % 2 == 0 for a in itertools.chain.from_iterable(x))

You need to actually iterate over the sublists.

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

Or you can you can take a much simpler approach.

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

The second approach uses the fact that in an integer context, True == 1 and False == 0 , so you would get the expected result.

You need to iterate over all the sublists:

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

You need to iterate over the elements in each sublist as well:

def count_evens(l):
    total = 0

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

    return total

What you were doing before was iterating over the number of sublists (ie [0, 1, 2, 3] for a list with 4 elements). Your code was working, but it wasn't working properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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