如何检查我的列表中是否已存在某个项目?

时间:2017-04-16 13:17:38

标签: python list tkinter listbox

我正在创建一个简单的GUI应用程序来管理未知单词,同时学习一门新语言。该应用程序称为词汇表,它从/向XML文档加载/保存单词。然而,每当我想在列表(框)中添加一个单词时,我想执行安全检查以查看该单词是否已存在于我的列表中。

这是我到目前为止所做的:

def add_item(self):

        if len(self.listBox.curselection()) > 0:
            messagebox.showinfo('Notification', 'Please make sure you have no words selected!')

        elif self.txt_WordOrPhrase['state'] == 'disabled':
            messagebox.showinfo('Notification', 'Please make sure you refresh fields first!')
        else:
            if len(self.txt_WordOrPhrase.get("1.0", "end-1c")) == 0:
                messagebox.showinfo('Notification', 'Please enter the word!')
            else:
                w = Word(self.get_word(), self.get_explanation(), self.get_translation(), self.get_example())
                if self.words: # check if an item already exists
                    self.words.append(w)
                    self.listBox.insert(END, w.wordorphrase)
                else:
                    messagebox.showinfo('Notification', 'That word already exists in your vocabulary!')

                self.clear_all()
                self.sync()
                self.word_count()

        self.save_all()

在C#中,我会这样做:

if (words.Find(x => x.WordOrPhrase == w.WordOrPhrase) == null) {
    words.Add(w);
    listView1.Items.Add(w.WordOrPhrase);
}

1 个答案:

答案 0 :(得分:0)

以下是整个解决方案:

def add_item(self):

        if len(self.listBox.curselection()) > 0:
            messagebox.showinfo('Notification', 'Please make sure you have no words selected!')

        elif self.txt_WordOrPhrase['state'] == 'disabled':
            messagebox.showinfo('Notification', 'Please make sure you refresh fields first!')
        else:
            if len(self.txt_WordOrPhrase.get("1.0", "end-1c")) == 0:
                messagebox.showinfo('Notification', 'Please enter the word!')
            else:
                w = Word(self.get_word(), self.get_explanation(), self.get_translation(), self.get_example())
                if not any(x for x in self.words if x.wordorphrase == w.wordorphrase):
                    self.words.append(w)
                    self.listBox.insert(END, w.wordorphrase)
                else:
                    messagebox.showinfo('Notification', 'That word already exists in your vocabulary!')

                self.clear_all()
                self.sync()
                self.word_count()

        self.save_all()