ValueError: list.remove(x): x 不在列表 python 中 [英] ValueError: list.remove(x): x not in list python

查看:62
本文介绍了ValueError: list.remove(x): x 不在列表 python 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从最小到最大整数对列表进行排序.不幸的是,当我尝试运行它时出现上述错误.

I'm trying to sort a list from smallest to biggest integers. Unfortunately I get the error stated above when I try to run it.

Traceback (most recent call last):
  File "lesson_4/selection_sort.py", line 24, in <module>
    print selection_sort([-8, 8, 4, -4, -2, 2]) # [-8, -4, -2, 2, 4, 8]
  File "lesson_4/selection_sort.py", line 14, in selection_sort
    lst.remove(min)
ValueError: list.remove(x): x not in list

这是 selection_sort.py 的代码

Here is the code of selection_sort.py

def selection_sort(lst):
  sorted = []
  list_len = len(lst) # Store this now because our loop will make it
                    # smaller
  min   = lst[0]
  i     = 1

  while list_len > 0:
    while i < list_len:
      item = lst[i]
      if item < min:
        min = item
      i += 1
    lst.remove(min)
    sorted.append(min)

  return sorted


# Test Code
print "Testing"


print selection_sort([-8, 8, 4, -4, -2, 2]) # [-8, -4, -2, 2, 4, 8]

感谢您帮助我!

推荐答案

在您第一次遍历列表时,您会找到最小元素.但是,在您的第二次 传递中,min 仍然设置为原始列表中的最小元素.结果,item 永远不会为真,并且 min 永远保持原始列表的最小元素.然后,当您尝试删除它时,您不能,因为您已经在上一次通过时删除了该项目(除非最小值存在并列,在这种情况下,一旦删除所有这些元素,就会发生这种情况).

On your first pass through the list, you find the minimum element. However, on your second pass, min is still set to the minimum element in the original list. As a result, item < min is never true, and min forever remains the minimum element of the original list. Then when you try to remove it, you can't, because you already got rid of that item on the previous pass (unless there is a tie for the minimum, in which case this will happen as soon as all those elements are removed).

要解决这个问题,只需将 min = lst[0] 移动到第一个循环中,这样每次都将其重置为有效值.

To solve this, just move min = lst[0] inside the first loop, so you reset it to a valid value each time.

您还有一些其他问题,我将在此处简要提及:

You've also got some other issues, which I will mention here briefly:

您永远不会更新 list_len,因此在第二次通过外循环(当您尝试超出列表长度时)结束时会出现错误.如果它没有破坏 bist,你也会永远循环.幸运的是,不需要整个变量:您可以在外部循环中使用 len(lst),并用以下内容替换内部 while 循环:

You never update list_len, so you'll get an error at the end of the second pass through the outer loop (when you will attempt to go beyond the length of the list). You'd also loop forever if it didn't break bist. Luckily this whole variable is unneeded: you can use len(lst) in the outer loop, and replace your inner while loop with this:

for item in lst:  # But see below regarding variable names!
    if item < min:
        min = item

这消除了单独跟踪 i 的需要,并避免了列表长度的任何问题.

This eliminates the need to track i separately and avoids any issues with the length of the list.

下一个:这看起来像家庭作业,所以此时它可能并不重要,但绝对值得一提:如果我将一个列表传递给一个名为 selection_sort 的函数,我会非常惊讶地发现,排序后,我原来的列表现在是空的!!除非您明确这样做(例如就地排序),否则修改输入通常是不好的形式,因此我强烈建议您在输入的副本上完成所有工作,以避免删除原来的所有内容:

Next: this looks like homework, so it's probably not critical at this moment, but it's definitely worth mentioning: if I pass a list to a function called selection_sort, I would be very surprised to discover that after being sorted, my original list is now empty!! It's generally bad form to modify an input unless you're doing so explicitly (e.g. an in-place sort), so I highly recommend that you do all your work on a copy of the input, to avoid deleting all the content of the original:

lst_copy = lst[:]  # If `lst` contains mutable objects (e.g. other lists), use deepcopy instead!
# Do stuff with lst_copy and avoid modifying lst

<小时>

最后,您有两个隐藏内置函数的变量:sortedmin.虽然这在技术上可行,但它的形式很差,最好养成不将局部变量命名为与内置变量相同的习惯.按照惯例,如果它确实是对象的最佳名称,您可以在名称中添加下划线以将其与内置函数区分开来:min_sorted_(或者更好, output),例如.


Finally, you've got two variables shadowing built-in functions: sorted and min. While this will technically work, it's poor form, and it's best to get into the habit of not naming local variables the same as builtins. By convention, if it's really the best name for the object, you can just add an underscore to the name to distinguish it from the builtin: min_ and sorted_ (or maybe better, output), for example.

这篇关于ValueError: list.remove(x): x 不在列表 python 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆