List 二维列表中项目的总和
我正在尝试实现一个函数evenrow(),该函数接受一个二维整数列表,如果表中的每一行总和为偶数,则返回True,否则返回False(即,如果某一行总和为奇数) 到目前为止,我得到的是:List 二维列表中项目的总和,list,python-3.x,2d,List,Python 3.x,2d,我正在尝试实现一个函数evenrow(),该函数接受一个二维整数列表,如果表中的每一行总和为偶数,则返回True,否则返回False(即,如果某一行总和为奇数) 到目前为止,我得到的是: def evenrow(lst): for i in range(len(lst)-1): if sum(lst[i])%2==0: # here is the problem, it only iterates over the first item i
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i])%2==0: # here is the problem, it only iterates over the first item in the lst [1, 3] - i cant figure this out - range problem?
return True
else:
False
如何让循环遍历列表中的每一项[1,3]、[2,4]、[0,6],而不仅仅是第一项
我已经走到了这一步:
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i]) %2 >0:
return False
else:
return True
当执行不同的列表时,我得到以下答案:
>>> evenrow([[1, 3], [2, 4], [0, 6]])
True
>>> evenrow([[1, 3], [3, 4], [0, 5]])
False
>>> evenrow([[1, 3, 2], [3, 4, 7], [0, 6, 2]])
True
>>> evenrow([[1, 3, 2], [3, 4, 7], [0, 5, 2]])
True
(最后一个不正确-应该是错误的)我不明白为什么这不起作用…你回来太早了。您应该检查所有对,之后只返回
True
,如果遇到奇数和,则返回False
扰流板警报:
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i]) % 2 != 0: # here is the problem, it only iterates over the first item in the lst [1, 3] - i cant figure this out - range problem?
return False
return True
这将实现目标。f sum(lst[i])%2 0:(无效语法)它不适用于这两种用法>>>evenrow([[1,3],[3,4],[0,5]])False>>>evenrow([[1,3],[2,4],[0,6]])>>>empty@Snarre编辑,使用python 2,可能是问题所在。
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i]) % 2 != 0: # here is the problem, it only iterates over the first item in the lst [1, 3] - i cant figure this out - range problem?
return False
return True