1

输入(列表)将是一个类似于 的列表[[1,2],[5,6],[4,6]]。我正在尝试将整行加在一起以测试它是偶数还是奇数。

def evenrow(list):
    for row in list:
        for item in row:
            newNums+=item
            n=sum(newNums)
            print(n)
4

3 回答 3

2

首先不要使用“列表”作为变量名。其次,您为 int 值而不是列表调用 sum,这就是您收到错误的原因。请检查您的代码。

不确定,但您的代码可能如下所示:

def evenrow(list):
    for row in list:
        value = sum(row)
        if values is even: # put your condition here
            # do something
        else:
            print "Value is odd"
于 2013-03-06T04:19:16.060 回答
1

只是另一种方法:

def evenrow(lst):
    return sum(map(sum,lst))%2 == 0 #True if even, False otherwise.

这是这样工作的:

外部sum将 的所有项目相加map,适用sum于 中的每个项目lst。在python2中,map返回一个list对象,而在python3中,它返回一个map对象。这被传递给外部sum函数,该函数将map.

def evenrow(lst):
    return sum(itertools.chain(*a)) % 2 == 0

这会扩展a(每个子列表)中的所有项目,并将它们链接在一起,作为一个chain对象。然后它将所有项目加在一起并确定总和是否为偶数。

于 2013-03-06T06:11:28.183 回答
0

You don't need the following line of code: n=sum(newNums). You already summed up all the items of row in the newNums += item line. Second, you have to declare newNums before using it in your code. So, the fixed version of code will look like this:

def evenrow(list):
    for row in list:
        newNums = 0
        for item in row:
            newNums += item
        print(newNums)

BTW: You should consider accepting answers to some of your previous questions, otherwise nobody will spend their time to answer your new questions.

于 2013-03-06T05:31:13.083 回答