Python:我的程序未正确执行for循环

时间:2019-11-27 08:43:34

标签: python

我有一个列表num_list,其中包含使用随机标识的随机数。 一个for循环负责从原始列表中选择数字,而我的compare函数应该将获得的数字与新列表中存在的数字进行比较。如果该数字大于从for循环获得的第一个数字,则检查相同的数字是否小于新列表中的下一个数字。这意味着num在数字之间,因此被插入其中。但是,我陷入了循环,无法理解发生了什么。我已经尝试了所有我知道的东西,但可悲的是,我仍然只是一个初学者。我希望这里的人可以把这个不幸的混乱弄成一团糟。

new_list.append((num_list)[0])

def compare(num, new_list, index, temp_char):
    for char in new_list:
        print(char)
        if num > char:
            index = new_list.index(char)
            try:
                temp_char = (new_list)[index + 1]
                if num <= temp_char:
                    new_list.insert(index+1, num)
            except:
                new_list.insert(index, num)

        break

for num in num_list:
    #print(num)
    compare(num, new_list, index, temp_char)
print(new_list)

1 个答案:

答案 0 :(得分:0)

正如Sayse在评论中所说,您不应在遍历列表时修改列表。这导致未定义的行为。相反,请在迭代列表之前复制列表new_list。要复制列表,有很多解决方案,但这是一个简单的解决方案:copied = [i for i in new_list]

如果您的列表是嵌套列表,则此方法将无效。

相关问题