[英]How to get each row in 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.
3 5 6 9 --> increasing 8 4 2 1 --> not increasing
"""
所以,我想使用sum()
,這是完全可行的,我想。
我開始是這樣的:
def increasing (m):
for row in m:
row[1]
但我知道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
假設你有一個函數“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
存儲最新的金額就足以得到答案:
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
您可以先創建rows
sums
的list
,然后檢查該list
是否正在增加。
def increasing(m):
sums = [sum(r) for r in m]
return all(sums[i] < sums[i+1] for i in range(len(m)-1))
我們可以用以下方法測試:
m1 = [[1, 3, 2, 5],
[7, 9, 4, 1],
[3, 5, 6, 9]]
m2 = [[2, 8, 4, 1],
[6, 2, 8, 5],
[8, 4, 2, 1]]
這會產生正確的結果:
>>> increasing(m1)
True
>>> increasing(m2)
False
只是做
row[0]+row[1]+row[2]+row[3]
求和過程和不知道行號的問題是通過迭代行來處理的,你不會有任何問題
來自sklearn導入預處理
import csv,sys
打開(“m.txt”)為f:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.