python-如何根据数据成员删除列表中的对象

时间:2014-04-20 17:46:15

标签: python

所以我在下面创建了这个类,并将它的实例存储在列表中。

class Word:
    def __init__(self,word,definition,synonyms):
        self.w=word
        self.defi=definition
        self.synonyms=synonyms

我确信我可以遍历列表并检查每个实例,但我正在尝试使用列表的remove方法。 x是Word对象列表

word="hi"
x.remove(Word if Word.w==word)
这给了我一个错误。那么有类似的方法吗?

EDIT 我试图简化我的问题,但显然我的意图并不明确。 我有一个字典,其键是单词的最后2个字母(用户添加),其值是具有最后2个字符的单词列表。例如:

w1=Word("lengthen","make something taller","some synonym")
w2=Word("woken","let someone wake up","some synonym")
w3=Word("fax","machine used for communication","some synonym")
w4=Word("wax","chemical substance","some synonym")
 ['en':(w1,w2),'ax':(w3,w4)] 

我正在尝试定义一个方法删除,它取字典和一个单词(STRING),然后它将删除包含以下单词的OBJECT Word。

def delete(dictionary,word):
    if word[-2:] in dictionary:
        x=dictionary[word[-2:]]
        if(x.count(word)!=0):
            x.remove(Word if Word.w==word)

2 个答案:

答案 0 :(得分:3)

你通常会使用列表推导来构建一个没有匹配的新列表,否则你最终会尝试修改列表而不是迭代它:

x = [word for word in x if word.w != "hi"]

注意小写word;使用Word遮蔽类本身。

如果就地更改列表至关重要,可以使用切片:

x[:] = [word for word in x if word.w != "hi"]

答案 1 :(得分:1)

我认为这会做你想做的事情:

class Word:
    def __init__(self,word,definition,synonyms):
        self.w=word
        self.defi=definition
        self.synonyms=synonyms
    def __repr__(self):  # added to facilitate printing of tuples of Word objects
        return 'Word({}, {}, {})'.format(self.w, self.defi, self.synonyms)

w1=Word("lengthen", "make something taller", "some synonym")
w2=Word("woken", "let someone wake up", "some synonym")
w3=Word("fax", "machine used for communication", "some synonym")
w4=Word("wax", "chemical substance", "some synonym")

dictionary = {'en': (w1, w2), 'ax': (w3, w4)}

def delete(dictionary, word):
    suffix = word[-2:]
    if suffix in dictionary:
        dictionary[suffix] = tuple(word_obj for word_obj in dictionary[suffix]
                                   if word_obj.w != word)

delete(dictionary, 'woken')
print(dictionary)