gpt4 book ai didi

python - 嵌套 for 循环索引超出范围

转载 作者:行者123 更新时间:2023-11-30 23:31:26 25 4
gpt4 key购买 nike

我遇到了一个相当微不足道的问题,但由于我对 python 很陌生,所以我有一段时间把头撞在 table 上。 (受伤)。虽然我相信这是一个更合乎逻辑的问题来解决......首先,我必须说我正在使用 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。你无法访问groups中第0个位置的东西,因为那里什么也没有!

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com