list.remove in can't 识别命令



我有一个名为"comms_chairs"的python列表,其结构如下:

[['  Chairwoman Debbie Stabenow ', 'Agriculture:'], ['  Chairman Tim Johnson' ',' 'Banking'], ['  Chairman Jay Rockefeller ', 'Commerce:'], ['  Chairman Jeff Bingaman', 'Energy:']

当我输入comms_chairs[0]时,我得到(如预期的)

['  Chairwoman Debbie Stabenow ', 'Agriculture:']

然而,当我试图从列表中删除字符串"Chairwoman"时,以下操作失败:

>>> type(comms_chairs[0])
<type 'list'>
>>> comms_chairs[0].remove(' Chairwoman')
Traceback (most recent call last):
 File "<pyshell#104>", line 1, in <module>
   comms_chairs[0].remove(' Chairwoman')
ValueError: list.remove(x): x not in list

当我不把空格放在Chairwoman之前时,也会出现同样的问题。这是怎么回事?在我看来,Chairwoman确实在comms_chairs[0]中。我的总体目标是删除所有Chairwoman和"主席"字符串,但了解列表的总体情况可能会有所帮助。如果不明显的话,我是Python的新手。

' Chairwoman'不在comms_chairs[0]中。它是comms_chairs[0][0]的子串,但不是comms_chairs[0]的元素。您遇到的问题类似于如果您只是尝试comms_chairs.remove(' Chairwoman')会遇到的问题。

要解决此问题,请使用列表理解过滤出包含' Chairwoman'的字符串,创建一个新列表,或者对这些字符串进行迭代(按相反的顺序,这样删除它们就不会干扰迭代),并删除每个包含' Chairwoman'的字符串。

这适用于第一个。

 b[0][0].replace(' Chairwoman ','')

comms_chairs[0]返回一个列表,因此您需要对其进行索引。

Soo。。。。字符串也是不可变的。这意味着如果你想让b[0][0]等于结果,你必须这样分配:

 b[0][0]=b[0][0].replace(' Chairwoman ','')

编写此

comms_chairs[0].remove('  Chairwoman Debbie Stabenow ')

还要注意,在开头和结尾都有一些空格。

最新更新