【问题标题】:sum of items in a 2d list二维列表中的项目总和
【发布时间】:2013-05-18 01:20:00
【问题描述】:

我正在尝试实现一个函数 evenrow(),它接受一个二维整数列表,如果表的每一行总和为偶数,则返回 True,否则返回 False(即,如果某些行总和为奇数数)

    usage
    >>> evenrow([[1, 3], [2, 4], [0, 6]])
    True
    >>> evenrow([[1, 3], [3, 4], [0, 5]])
    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 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

(虽然最后一个不正确 - 应该是错误的)我只是不明白为什么这不起作用......

【问题讨论】:

    标签: list python-3.x 2d


    【解决方案1】:

    你回来得太早了。您应该检查所有对,之后只返回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]]) >>> # 空
    • @Snarre 已编辑,使用的是 python 2,可能是问题所在。
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2020-05-22
    相关资源
    最近更新 更多