使用python查找列表中是否存在item的变量

时间:2015-10-30 17:45:44

标签: python

如何使用python检查列表中的对象是否已包含相同的名称?

  • 班级对象团队
    • 属性:名称

我有一个包含多个'团队'的列表

伪代码

var DB_NAME = 'test', DB_VERSION = 1, NEW_DB_VERSION = 2;
indexedDB.deleteDatabase(DB_NAME);

var data = [{
    firstName: 'Brett',
    lastName: 'Zamir',
    age: 43
}, {
    firstName: 'Jane',
    lastName: 'Doe',
    age: 40
}, {
    firstName: 'Bob',
    lastName: 'Doe',
    age: 42
}];

var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onerror = function (evt) {
    console.error("openDb:", evt.target.errorCode);
};
req.onsuccess = function (evt) {
    var db = this.result;

};
req.onupgradeneeded = function (e) {
    var db = e.target.result;
    var os = db.createObjectStore('test', {
        keyPath: 'id',
        autoIncrement: true
    });
    os.transaction.oncomplete = function () {
        var testTx = db.transaction('test', 'readwrite');
        testTx.oncomplete = function () {
            console.log('storage completed');
            fireBlockedEvent(db);
        };
        var testStore = testTx.objectStore('test');
        for (var i in data) {
            testStore.add(data[i]);
        }
    };
};

function fireBlockedEvent (db) {
    var req = indexedDB.open(DB_NAME, NEW_DB_VERSION);
    req.onblocked = function () {
        console.log('blocked');
        db.close();
        var req = indexedDB.deleteDatabase(DB_NAME);
        req.onsuccess = function () {
            console.log('we ok');
        };
        req.onblocked = function () {
            console.log('still blocked');
        };
    };
}

我如何测试团队'Browns'是否已经存在? 它只是一个简单的for循环逐项,或者python是否有一些短代码来执行此操作?

2 个答案:

答案 0 :(得分:2)

如果团队名称是定义相等的名称,您可以执行以下操作:

class Team(object):
    def __eq__(self, other_team):
        return self.name == other_team.name

然后您只需执行if team in teams(其中,团队是Team的实例,teamsTeam的实例列表)。

答案 1 :(得分:0)

列表看起来不是pythony,但如果我们假设它是,那么这就是方法:

class Team:
    def __init__(self, name):
        self.name = name

teams = [Team("Dolphins"), Team("Browns"), Team("Ravens")]

def checkIfNameExists(team_obj_list, the_name):
    for team in team_obj_list:
        if (team.name == the_name):
            return "Name " + the_name + " already exists"

print checkIfNameExists(teams, "Browns")