2015-08-20 51 views
3

我怎樣寫替換與0
這裏陣列中的所有負數的功能是什麼,我到目前爲止有:在Array更換否定,巨蟒

def negativesToZero(A): 
    for x in A: 
     if x < 0: 
      A.append(0) 
    else: 
     pass 
    print A 
A = ([[1,-2],\ 
     [-2,1]]) 
negativesToZero(A) 
+2

搶筆和紙並手動通過這些代碼。你會發現它做了一些你不想要的奇怪的事情。 – TigerhawkT3

+0

這適用於2維int列表,如A:[list(map(lambda x:x if x> = 0 else -x,a))for a] –

回答

4

由於A是名單清單:

>>> A = [[1, -2], [-2, 1]] 

>>> for lst in A: 
...  for i, val in enumerate(lst): 
...   lst[i] = max(val, 0) 

>>> print A 
[[1, 0], [0, 1]] 

或者應用列表解析:

>>> A = [[max(val, 0) for val in lst] for lst in A] 
0

經過每個s在list的ublist。對於每個子列表,創建一個將任何負項目轉換爲0的新項目。最整潔的方法是使用一個理解:

A = [[1,-2], [-2,1]] 
A = [[item if item >= 0 else 0 for item in l] for l in A] 

結果:

[[1, 0], [0, 1]] 
0

這裏是一個遞歸實現,將與任何類型列表中的工作,與在任何類型的輸入:

def convertToZero(arr): 
    for i in range(len(arr)): 
     if type(arr[i]) == int and arr[i] < 0: 
      arr[i] = 0 
     elif type(arr[i]) == list: 
      convertToZero(arr[i]) 
    return arr 

result = convertToZero([[1,-2], ['hello',[-2,1]], [-1,'world']]) 
print result 
# [[1, 0], ['hello', [0, 1]], [0, 'world']] 
0

下面是一個簡單和容易相處的你試圖做的線條理解答案在開始的時候:

def negativesToZero(A): 
    index = 0 #Track your index 

    for x in A: 
     if isinstance(x, list): #Calling the program recursively on nested lists 
      A[index] = negativesToZero(x) 

     elif x < 0: 
      A[index] = 0 #Makes negatives 0 

     else: 
      pass #Ignores zeros and positives 

     index += 1 #Move on to next index 
    print A 
    return A 

如果你不想不必要的內打印語句,你可以添加一個輸入變量(我將其稱爲「復發」),以使只有非遞歸調用打印功能:

def negativesToZero(A, recur = False): 
    index = 0 

    for x in A: 
    if isinstance(x, list): 
     A[index] = negativesToZero(x, True) 

    elif x < 0: 
     A[index] = 0 

    else: 
     pass 

    index += 1 
    if recur == False: print A 
    return A 

結果:

A = ([[1,-2],\ 
    [-2,1],\ 
    [-5, -6], [4,7]]) 

negativesToZero(A) 

>>>> [[1, 0], [0, 1], [0, 0], [4, 7]] 
0
import numpy as np 

listOnums = np.random.normal(size = 300) 
listOnums = listOnums.reshape(3,10,10) 


def negToZero(arrayOnums): 
    ''' 
    Takes an array of numbers, replaces values less than 0 with 0 
    and retuns an array of numbers. 
    ''' 
    dims = arrayOnums.shape 
    flatNums = arrayOnums.flatten() 

    for num,x in enumerate(flatNums): 

     if x >= 0: pass 
     else: 
      flatNums[num] = 0 

     arrayOnums = flatNums.reshape(dims) 

    return arrayOnums 

negToZero(listOnums) 
+0

希望這個更清楚,如果我拼出來,循環可以完全替換爲列表理解。 – memebrain

1

如果你想要一個一個rray操作,你應該創建一個適當的數組來開始。

A=array([[1,-2],[-2,1]]) 

陣列內涵像你可以使用在指數布爾操作的一個內襯:

A[A<0]=0 

當然,你可以鏡框作爲一個功能:

def positive_attitude(x): 
    x[x<0]=0 
    return x 
print positive_attitude(A)