2016-04-30 35 views
0

我有一個數組,看起來像這樣:Python 2.7版:在2D Python的陣列評估對

myarray = array([[Me, False], [Me, True], [Partner, False], [Me, True], [Me, False],[Me, True],[Partner, True]]) 

我想要做的就是每次啓動計數器[我,真]顯示,使該計數器增加,直到數組中出現[Partner,True]或[Partner,False]。每當此計數器遇到[Partner,True]或[Partner,False]時,都應該重置。

所以,如果permcount = 0和tempcount = 0,

在上述例子中,因爲[Me中,真]正好出現之前[合作伙伴,FALSE],tempcount將遞增到1,然後得到加時permcount [合作伙伴,FALSE]遇到和復位爲0。

現在permcount = 1和tempcount = 0

當[Me中,真]旁邊出現,tempcount會遇到[合作伙伴,真]和復位之前達到3到0和permcount = 4.

我的代碼如下所示:

tempcount = 0 
permcount = [] 
flag = True 
initiated = False 

for x,y in myarray: 
    if x == "Me" and y == True: 
     if flag == True: 
      tempcount = tempcount + 1 
      initiated == True 
     else: 
      tempcount = 0 
      tempcount = tempcount + 1 
      flag == True 
    if x == "Me" and y == False and flag == True and initiated == True: 
     tempcount = tempcount + 1 
    if x == "Partner" and y == True and flag == True and initiated == True: 
     permcount.append(tempcount) 
     flag == False 
    if x == "Partner" and y == False and flag == True and initiated == True:  
     permcount.append(tempcount) 
     flag == False 

出於某種原因,這似乎並沒有評估和追加tempcount在所有的permcount仍處於結束時清空。我做錯了什麼建議?

編輯:的確,這不是一個Numpy數組...我通過一個pandas dataframe.values命令實現了這個列表清單。還爲稍後將看到此內容的任何用戶更正了一些拼寫錯誤。感謝你們!

-Mano

+1

我在這裏看不到任何'numpy'數組的使用;這很好,因爲'np.append'不像列表追加那樣工作。此外,對於像「我」和「真」這樣的值,列表或列表的列表優於陣列。至於問題 - 您需要打印一些中間結果。 – hpaulj

+0

您能提供一些預期輸出嗎? – Eric

+2

'initiate == True '應該是'啓動=真',並且同樣爲'Flag == True' – Eric

回答

1

首先我數組改爲

alist = [["Me", False], ["Me", True],... 

如果沒有進一步的變化,我得到3 tempcount[]permcount

改變這些錯位的===,這意味着將那些改變flagintiated值(而不是對它們進行測試),我得到

3 
[1, 3] 

== True般的表情可以簡化(雖然它不會改變結果)

for x,y in alist: 
    if x == "Me" and y: 
     if flag: 
      tempcount += 1 
      initiated = True 
     else: 
      tempcount = 1 
      flag = True 
    if x == "Me" and not y and flag and initiated: 
     tempcount += 1 
    if x == "Partner" and y and flag and initiated: 
     permcount.append(tempcount) 
     flag = False 
    if x == "Partner" and not y and flag and initiated:  
     permcount.append(tempcount) 
     flag = False 
+0

啊!該死的我沒有意識到==和=之間的區別,非常感謝你,像一個魅力一樣!Mano – manofone