简体   繁体   English

简单的python嵌套循环-索引超出范围

[英]Simple python nested loops - index out of range

When I run the following code, I get an error: 当我运行以下代码时,出现错误:

def genSet(nums):
    for i in range(0, len(nums)-1):
        for x in range(0, len(nums)-1):
            if nums[x] == nums[i]:
                del nums[x] 
    return nums

a = [5, 4, 3, 5, 6, 7, 8, 5, 4, 3]  
print genSet(a)

Output: 输出:

Traceback (most recent call last):
  File "49.py", line 9, in <module>
    print genSet(a)
  File "49.py", line 4, in genSet
    if nums[x] == nums[i]:
IndexError: list index out of range

As far as I can tell (I replaced the if statement with "print x, i") the two for loops are fine, so why is the index out of range? 据我所知(我将if语句替换为“ print x,i”),两个for循环都很好,为什么索引超出范围?

don't do del nums[x] , since this way you make nums shorter and thus get an exception. 不要执行del nums[x] ,因为这样可以使nums变短,从而导致异常。

you can simply make a set out of the list by set_nums = set(nums) 您可以通过set_nums = set(nums)从列表中简单地进行设置

You are removing elements from nums , therefore it becomes shorter and an IndexError occures. 您正在从nums中删除元素,因此它变短了,并发生了IndexError。

Anyway, your code would remove everything, because every element has as least one identical element in the list (itself!). 无论如何,您的代码将删除所有内容,因为每个元素在列表中至少具有一个相同的元素(本身!)。 If you want to create a "unique" list of elements, create a set: 如果要创建元素的“唯一”列表,请创建一个集合:

unique_set = set(nums)

and convert it to list again: 并将其转换为再次列出:

unique_list = list(set(nums))

您可以找到数字相同的索引,将列表创建为numpy数组nums = np.array(nums)并使用np.delete命令。

The example you give can be simply replaced by a one-line code: 您提供的示例可以简单地用一行代码代替:

print set([5, 4, 3, 5, 6, 7, 8, 5, 4, 3])

If I really want filter out the duplicates in a list myself, I would: 如果我真的想自己过滤掉列表中的重复项,我将:

nums = sorted([5, 4, 3, 5, 6, 7, 8, 5, 4, 3])
print reduce(lambda x,y:(y not in x and x+[y]) or x, nums, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM