如何在Python中获取每一行?
我需要这样做:如何在Python中获取每一行?,python,Python,我需要这样做: """ Program a function def increasing (m) 对于任何正整数矩阵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.
"""
Program a function
def increasing (m)
对于任何正整数矩阵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
"""
def increasing(m):
sums = [sum(r) for r in m]
return all(sums[i] < sums[i+1] for i in range(len(m)-1))
所以,我想使用sum()
,我想这是完全可行的
我是这样开始的:
def increasing (m):
for row in m:
row[1]
但我知道第[1]行只会输出每行索引中的数字。我的想法是:
def increasing (m):
for row in m:
if sum(row)[first_row] > sum(row)[second_row]:
return False
但这只是切片,所以我不知道如何计算行数以便比较它们
我不想使用任何模块或任何东西,只是简单的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
您可以执行以下操作:
def increasing(m):
return all(sum(r1) < sum(r2) for r1, r2 in zip(m, m[1:]))
只需存储最新的总和即可获得答案:
def increasing(m):
last_sum = -float('inf')
for row_sum in map(sum, m):
if row_sum < last_sum:
return False
last_sum = row_sum
return True
def增加(m):
last_sum=-float('inf')
对于图中的行和(和,m):
如果行总和<最后一行总和:
返回错误
最后的总和=行总和
返回真值
只要做就行了
row[0]+row[1]+row[2]+row[3]
对于求和过程,不知道行号的问题是通过对行进行迭代来处理的,假设您有一个函数“sum”返回给定行的和,您将不会有任何问题。 您可以使用temp变量来保持当前行的总和,并将其用于验证。 对于exmaple:
def increasing (m):
prevRow = 0
currentRow = 0
for row in m:
currentRow = sum(row)
if (currentRow <= prevRow):
return False
prevRow= currentRow
else:
return True
def增加(m):
prevRow=0
currentRow=0
对于以m为单位的行:
currentRow=总和(行)
如果(currentRow,您可以首先创建行的和的列表,然后检查该列表是否在增加
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
"""
def increasing(m):
sums = [sum(r) for r in m]
return all(sums[i] < sums[i+1] for i in range(len(m)-1))
这将产生正确的结果:
>>> increasing(m1)
True
>>> increasing(m2)
False
从sk学习导入预处理
导入csv,系统
将open(“m.txt”)作为f:
您的输入格式是什么样的?添加了@hamedtemsah,-float('inf')有什么作用?我不明白。@Siyah,这个表达式相当于“负无穷大”。在这里,它用于避免对第一排进行特殊处理。有趣。以前从未听说过。谢谢@Elisha!嗨,谢谢。如果我不想使用zip怎么办?还有什么选择?这比necessary@JoeIddon是的,但我会保留它,否则它会失去一些简洁性和直观可读性。@schwo是的,这确实是一个非常聪明的答案:)我不明白这是怎么回事。当我这样做的时候,它只是显示每一行的第一个数字,这不是我想要的。啊,尽管它比其他答案长一点,但我喜欢简洁明了的方式。非常感谢你!很高兴能帮上忙,我只是想澄清一下,schwobaseggl的答案更像“Pythonic”,而我的答案更像香草。仅供参考。
reader = csv.reader(f)
next(reader) # skip header
data = [r for r in reader]
data.pop(0)
print(type(data))
a=np.asarray(data)
print(np.nanvar(a,ddof=1))