我提出了一个相当琐碎的问题,但是由于我是python的新手,所以我将头砸到桌子上了一段时间。 (伤害)。尽管我认为这是更合乎逻辑的解决方案...
首先,我不得不说我使用的是适用于Cinema 4D的Python SDK,因此我不得不稍作更改。但是,这是我一直在努力并努力解决的问题:
我正在尝试对一些多边形选择进行分组,这些多边形选择是动态生成的(基于某些规则,并不那么重要)。
这是数学方式的工作方式:
这些选择基于岛屿(即,有多个多边形连接)。
然后,必须将这些选择分组并放入我可以使用的列表中。
任何多边形都有自己的索引,因此这个索引应该很简单,但是就像我之前说过的那样,我在这里苦苦挣扎。

主要问题很容易解释:我试图在第一个循环中访问不存在的索引,导致索引超出范围错误。我尝试先评估有效性,但没有运气。对于那些熟悉Cinema 4D + Python的人,如果有人需要,我将提供一些原始代码。到目前为止,太糟糕了。这是经过简化和改编的代码。

编辑:忘记提及导致错误的检查实际上只应检查重复项,因此将跳过当前选定的编号,因为它已被处理。由于计算量大,这是必需的。

真希望,任何人都可以向正确的方向撞我,到目前为止,这段代码是有意义的。 :)

def myFunc():

        sel = [0,1,5,12] # changes with every call of "myFunc", for example to [2,8,4,10,9,1], etc. - list alway differs in count of elements, can even be empty, groups are beeing built from these values
        all = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # the whole set
        groups = [] # list to store indices-lists into
        indices = [] # list to store selected indices
        count = 0 # number of groups
        tmp = [] # temporary list to copy the indices list into before resetting

        for i in range(len(all)): # loop through values
            if i not in groups[count]: # that's the problematic one; this one actually should check whether "i" is already inside of any list inside the group list, error is simply that I'm trying to check a non existent value
                for index, selected in enumerate(sel): # loop through "sel" and return actual indices. "selected" determines, if "index" is selected. boolean.
                    if not selected: continue # pretty much self-explanatory
                    indices.append(index) # push selected indices to the list
                tmp = indices[:] # clone list
                groups.append(tmp) # push the previous generated list to another list to store groups into
                indices = [] # empty/reset indices-list
                count += 1 # increment count
        print groups    # debug
myFunc()


编辑:

添加第二个列表后,该列表将由extend(而不是用作计数器的append)填充,一切按预期进行!该列表将是一个基本列表,非常简单;)

最佳答案

groups[count]


当您第一次调用此命令时,groups是一个空列表,count为0。您无法访问组中位于0点的东西,因为那里什么也没有!

尝试制作
groups = []groups = [[]](即不是一个空列表,而是一个只有一个空列表的列表的列表)。

关于python - 嵌套的循环索引超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19941504/

10-14 18:12
查看更多