如何在Python中获取每一行?

Siy*_*yah 2 python

我需要这样做:

"""
Program a function

    def increasing (m)
Run Code Online (Sandbox Code Playgroud)

对于任何正整数矩阵m,它将能够检查该数组中行的总和是否在增加.

examples
1 3 2 5        The sums of the rows        2 8 4 1        The sums of the rows
7 9 4 1        are 11, 21 and 23.          6 2 8 5        are 15, 21 and 15.
3 5 6 9        --> increasing              8 4 2 1        --> not increasing
"""
Run Code Online (Sandbox Code Playgroud)

所以,我想使用sum(),这是完全可行的,我想.

我开始是这样的:

def increasing (m):
    for row in m:
        row[1]
Run Code Online (Sandbox Code Playgroud)

但我知道row [1]只会输出每行索引 1中的数字.我的想法是:

def increasing (m):
    for row in m:
        if sum(row)[first_row] > sum(row)[second_row]:
           return False
Run Code Online (Sandbox Code Playgroud)

但这只是切片,所以我不知道如何计算行数,以便我可以比较它们.

我不想使用任何模块或任何模块,只是简单的Python.有人能指出我正确的方向吗?我只需要它尽可能简单.

输入格式示例:

increasing_l = [
    [1, 3, 2, 5],
    [7, 9, 4, 1],
    [3, 5, 6, 9]
]

not_increasing_l = [
    [2, 8, 4, 1],
    [6, 2, 8, 5],
    [8, 4, 2, 1]
]

test1 = increasing(increasing_l)
test2 = increasing(not_increasing_l)

print "should be True: %s" % test1
print "should be False: %s" % test2
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 10

您可以执行以下操作:

def increasing(m):
    return all(sum(r1) < sum(r2) for r1, r2 in zip(m, m[1:]))
Run Code Online (Sandbox Code Playgroud)

这用于zip配对相邻行并all有效地进行成对和比较.

没有zip:

return all(sum(m[i-1]) < sum(m[i]) for i in range(1, len(m)))
Run Code Online (Sandbox Code Playgroud)


小智 7

假设你有一个函数"sum",它返回给定行的总和.您可以使用临时变量来保留当前行的总和并将其用于验证.例如:

def increasing (m):
    prevRow = 0
    currentRow = 0
    for row in m:
        currentRow = sum(row)
        if (currentRow <= prevRow):
           return False
        prevRow= currentRow
    else:
        return True
Run Code Online (Sandbox Code Playgroud)