简体   繁体   English

ValueError:list.remove(x):x不在列表中

[英]ValueError: list.remove(x): x not in list

What is wrong in my code, but I can get my expected result. 我的代码有什么问题,但我可以得到预期的结果。

I am trying to remove all "#" in the list. 我想删除列表中的所有“#”。

funds_U is the list of data: funds_U是数据列表:

In [3]: funds_U
Out[3]: 
[u'#',
 u'#',
 u'MMFU_U',
 u'#',
 u'#',
 u'AAI_U',
 u'TGI_U',
 u'JAS_U',
 u'TAG_U',
 u'#',
 u'#',
 u'AAT_U',
 u'BGR_U',
 u'BNE_U',
 u'IGE_U',
 u'#',
 u'#',
 u'DGF_U',
 u'BHC_U',
 u'FCF_U',
 u'SHK_U',
 u'VCF_U',
 u'#',
 u'JEM_U',
 u'SBR_U',
 u'TEM_U',
 u'#',
 u'#',
 u'BAB_U',
 u'BGA_U',
 u'#']

The following is the code: 以下是代码:

In [4]: for fund_U in funds_U[:]:
   ...:     funds_U.remove(u"#")
   ...:     

The following is the error: 以下是错误:

ValueError                                Traceback (most recent call last)
<ipython-input-4-9aaa02e32e76> in <module>()
      1 for fund_U in funds_U[:]:
----> 2     funds_U.remove(u"#")
      3 

ValueError: list.remove(x): x not in list

As per the documentation , if the item doesn't exist in the list, remove() will throw an error. 根据文档 ,如果列表中不存在该项,则remove()将引发错误。 Right now your code iterates through every item in the list and tries to remove that many # s. 现在通过在列表中的每一项你的代码进行迭代,并尝试删除许多#秒。 Since not every item is a # , remove() will throw an error as the list runs out of # s. 因为不是每一个项目是一个#remove()为列表用完就会报错#秒。

Try a list comprehension like this: 尝试这样的列表理解

funds_U = [x for x in funds_U if x != u'#']

This will make a new list that consists of every element in funds_U that is not u'#' . 这将创建一个新的列表,其中包含funds_U中不是u'#'的每个元素。

I would do this so: 我会这样做:

new = [item for item in funds_U if item!=u'#']

This is a list-comprehension . 这是列表理解 It goes through every item in funds_U and adds it to the new list if it's not u'#' . 它遍历funds_U中的每个项目,如果它不是u'#'则将其添加到新列表中。

这将修改原始对象,因此如果有其他变量指向同一对象,则其链接将保持不变。

FUNDS_U[:] = [x for x in FUNDS_U if x != "#"]

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

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