2016-10-10 124 views
0

我有一個關於python和選擇範圍內的元素的問題。Python - 從範圍內的矩陣中選擇元素

如果我有一個有n行m列的n×m矩陣,我有一個爲每列定義的範圍(所以我有m最小值和最大值)。

現在我想選擇那些行,其中所有的值都在範圍內。

看下面的例子:

input = matrix([[1, 2], [3, 4],[5,6],[1,8]]) 
boundaries = matrix([[2,1],[8,5]]) 
#Note: 
#col1min = 2 
#col1max = 8 
#col2min = 1 
#col2max = 5 
print(input) 

desired_result = matrix([[3, 4]]) 
print(desired_result) 

在這裏,3行,其中丟棄,因爲它們含有超出了界限值。

雖然我能夠獲得給定數組的一個範圍內的值,但我沒有設法有效地解決這個問題。

謝謝你的幫助。

+0

簡要解釋你的問題! –

回答

0

我相信有更優雅的解決方案,但是我來到了這一點:

def foo(data, boundaries): 
    zipped_bounds = list(zip(*boundaries)) 
    output = [] 
    for item in data: 
     for index, bound in enumerate(zipped_bounds): 
      if not (bound[0] <= item[index] <= bound[1]): 
       break 
     else: 
      output.append(item) 
    return output 

data = [[1, 2], [3, 4], [5, 6], [1, 8]] 
boundaries = [[2, 1], [8, 5]] 
foo(data, boundaries) 

輸出:

[[3, 4]] 

而且我知道有沒有檢查和引發異常,如果的大小數組不會匹配每個具體的大小。我讓它執行此操作。

0

您的數據。例如語法不正確matrix([[],..])所以還需要進行重組,這樣的:

matrix = [[1, 2], [3, 4],[5,6],[1,8]] 
bounds = [[2,1],[8,5]] 

我不知道你所說的「高效」的意思是什麼,但這種方法是可讀的,計算效率和模塊化:

# Test columns in row against column bounds or first bounds 
def row_in_bounds(row, bounds): 
    for ci, colVal in enumerate(row): 
     bi = ci if len(bounds[0]) >= ci + 1 else 0 
     if not bounds[1][bi] >= colVal >= bounds[0][bi]: 
      return False 
    return True 

# Use a list comprehension to apply test to n rows 
print ([r for r in matrix if row_in_bounds(r,bounds)]) 
>>>[[3, 4]] 

首先,我們創建了行接受範圍列表的列表可重複使用的測試功能,元組可能更合適,但我還是堅持了列表按您的規範。

然後將這個測試應用到你的列表理解的n行矩陣中。如果n超出邊界列索引或邊界列索引爲false,請使用提供的第一組邊界。

將行迭代器保留在行解析器函數之外允許您根據需要執行諸如從過濾元素中獲取min/max之類的操作。這樣你就不需要爲每個所需數據的操作定義一個新的函數。