问题描述
我正在尝试从列表中删除一个元组.如果列表中的第一个元素等于"-NONE-",我想删除整个元组.尝试其他操作时,我总是收到错误消息.这就是我所拥有的:
I'm trying to remove a tuple from a list. If the first element in the list equals "-NONE-" I want to remove the whole tuple. I keep getting an error when I try different things. Here's what I have:
def filter(sent):
for tuple in sent:
if tuple[1] == "-NONE-":
sent.remove(sent.index(tuple))
我正在使用此测试来调用方法:
I'm using this test to call the method:
filter([('uh', 'UH'), ('i', 'PRP'), ('think', 'VBP'), (',', ','), ('*0*', '-NONE-'), ('it', 'PRP'), ("'s", 'BES'), ('because', 'IN'), ('i', 'PRP'), ('get', 'VBP'), ('*', '-NONE-'), ('to', 'TO'), ('be', 'VB'), ('something', 'NN'), ('that', 'WDT'), ('i', 'PRP'), ("'m", 'VBP'), ('not', 'RB'), ('*T*', '-NONE-'), ('.', '.')])
但我不断收到此错误:
Traceback (most recent call last):
File "<pyshell#273>", line 1, in <module>
filter([('uh', 'UH'), ('i', 'PRP'), ('think', 'VBP'), (',', ','), ('*0*', '-NONE-'), ('it', 'PRP'), ("'s", 'BES'), ('because', 'IN'), ('i', 'PRP'), ('get', 'VBP'), ('*', '-NONE-'), ('to', 'TO'), ('be', 'VB'), ('something', 'NN'), ('that', 'WDT'), ('i', 'PRP'), ("'m", 'VBP'), ('not', 'RB'), ('*T*', '-NONE-'), ('.', '.')])
File "<pyshell#272>", line 4, in filter
sent.remove(sent.index(tuple))
ValueError: list.remove(x): x not in list
推荐答案
remove
方法采用要从列表中删除的对象,而不是索引.您可以使用具有索引的del
,也可以将元组直接传递给remove
:
The remove
method takes an object to remove from the list, not an index. You could either use del
, which does take an index, or pass the tuple to remove
directly:
def filter(sent):
for tuple in sent:
if tuple[1] == "-NONE-":
# del sent[sent.index(tuple)]
sent.remove(tuple)
但是,这仍然行不通.您要在迭代列表时对其进行修改,这会弄乱您在迭代中的位置.另外,index
和remove
都很慢,并且将函数filter
命名为隐藏内置的filter
函数是一个坏主意.最好使用列表理解功能创建一个新的,经过过滤的列表:
However, this still won't work. You're modifying the list while iterating over it, which will screw up your position in the iteration. Also, both index
and remove
are slow, and it's a bad idea to name a function filter
, hiding the built-in filter
function. It would most likely be better to create a new, filtered list with a list comprehension:
def filtered(sent):
return [item for item in sent if item[1] != "-NONE-"]
这篇关于从列表中删除元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!