Python枚举时从数组中删除

2024-10-02 10:24:01 发布

您现在位置: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.

我知道发生此错误是因为我试图从数组中删除对象,同时也枚举这些对象。但我不知道怎么解决。我对面向对象编程还比较陌生,现在只限于编写脚本。你知道吗

我搜索了网页,似乎解决了这个错误,我必须复制数组,然后再从中删除对象。当我准备通过deepcopy复制数组时

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

就在for path in thisLayer.paths:之前

但在这种情况下,我得到以下错误:

Cannot pickle Objective-C objects

通常程序在第一个Glyph之后崩溃。澄清一下:我在Glyphsapp工作,这是一个字体设计软件。你知道吗

代码如下:

# 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

先谢谢你


Tags: path对象inpyfor错误line数组
1条回答
网友
1楼 · 发布于 2024-10-02 10:24:01

非常感谢安德烈亚斯

在你的帮助下,我可以修复我的代码:-)

结果如下:

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 )

相关问题 更多 >

    热门问题