2016-02-11 65 views
1

錯誤從數組中刪除:Python的同時枚舉

Traceback (most recent call last): 
    File "<string>", line 10, in <module> 
    File "/Users/georg/Programmierung/Glyphs/Glyphs/Glyphs/Scripts/GlyphsApp.py", line 59, in __iter__ 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_convenience.py", line 589, in enumeratorGenerator 
    yield container_unwrap(anEnumerator.nextObject(), StopIteration) 
objc.error: NSGenericException - *** Collection <__NSArrayM: 0x7f9906245480> was mutated while being enumerated. 

我知道,因爲我想從數組中刪除的對象,同時還列舉這些對象出現此錯誤。但我不知道如何解決它。我對面向對象的編程還很陌生,並且將自己限制爲腳本編寫。

我搜索了網頁,它似乎解決了錯誤,我必須複製數組之前刪除對象。當我綁到前for path in thisLayer.paths:

但在這種情況下,我得到以下錯誤權的陣列通過deepcopy的

import copy 
pathcopy = copy.deepcopy(thisLayer.paths) 

複製:

Cannot pickle Objective-C objects 

一般先雕文後的程序崩潰。澄清:我在Glyphsapp(一款Typedesigning軟件)工作。

這裏是代碼:

# loops through every Glyph and deletes every path with nodes on the left half 
    for myGlyph in Glyphs.font.glyphs: 
     glname = myGlyph.name 
     thisLayer = Glyphs.font.glyphs[glname].layers[1] 
     middle = thisLayer.bounds.size.width/2+thisLayer.LSB 
     thisGlyph = thisLayer.parent 

     for path in thisLayer.paths: # this is where the code crashes 
      for thisNode in path.nodes: 
       if thisNode.position.x < middle: 
        #print thisNode.position.x 
        try: 
         thisLayer = path.parent() 
        except Exception as e: 
         thisLayer = path.parent 
        try: 
         thisLayer.removePath_ (thisNode.parent()) 
        except AttributeError: 
         pass 

預先感謝您

+0

您可以將要刪除的項目收集到一個單獨的列表中,然後使用另一個循環來覆蓋該列表以在thisLayer中刪除它們。 –

回答

0

非常感謝您安德烈亞斯,

在您的幫助,我能夠解決我的代碼:-)

結果如下:

for myGlyph in Glyphs.font.glyphs: 
    glname = myGlyph.name 
    thisLayer = Glyphs.font.glyphs[glname].layers[1] 
    middle = thisLayer.bounds.size.width/2+thisLayer.LSB 
    thisGlyph = thisLayer.parent 

    for path in thisLayer.paths:  
     for thisNode in path.nodes: 
      if thisNode.position.x < middle: 
       nodeList = [] 
       nodeList.append(thisNode.parent()) 
    nLCopy = nodeList[:] 
    for ncontainer in nLCopy: 
     thisLayer.removePath_ (ncontainer)