简体   繁体   English

在二维列表中计算偶数?

[英]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. 当我希望它返回4时,它总是返回2的清单Evens([[1,3],[1,9,7,1,3],[13]]) 。工作正常。

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: IMO更简单的方法是:

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. 第二种方法使用的事实是,在整数上下文中, True == 1False == 0 ,因此您将获得预期的结果。

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). 您之前所做的是遍历子列表的数量(例如[0, 1, 2, 3]对于具有4元素的列表[0, 1, 2, 3] )。 Your code was working, but it wasn't working properly. 您的代码可以正常工作,但是不能正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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