在对象列表中查找行

时间:2017-08-23 17:50:28

标签: python-2.7

需要你的帮助。有一个由类对象组成的列表(数组),如何在此列表中查找项(行),例如:手机或名称?我有一个函数findByNamefindByPhone它们不起作用!

class Database:
    name = 'n/a'
    phone = 'n/a'
    list = []
    copy_list = []

    class Rec:
        def __init__(self, nam, phon):
            self.name = nam
            self.phone = phon
        def __str__(self):
            return "%s, %s" % (self.name, self.phone)
    def __init__(self, fileName):
        pass
    def addRecord(self, name, phone):
        self.list.append(Database.Rec(name,phone))
    def findByName(self, name):
        res = self.findSubStr(name)
        if len(res) == 0:
            print ("Sorry, nothing match in names for " + name)
        return res
    def findByPhone(self, phone):
        res = self.findSubStr(phone)
        if len(res) == 0:
            print ("Sorry, nothing match in phones for " + phone)
        return res
    def findSubStr(self, substr):
        res = []
        for el in self.list:
            if substr in self.list:
                res.append(el)
        return res
def fun_input():
    print ("Please enter the name")
    name = raw_input()
    print ("Please enter phone number")
    phone = raw_input()
    db.addRecord(name, phone)
def fun_output():
    db.out()
def fun_find():
    print ("Please choose an option for which you want to search:")
    print ("1 - Find for name")
    print ("2 - Find for phone number")
            ph = int(raw_input())
            if ph == 1:
            print ("Please enter the name for find:")
            phName = raw_input()
            db.findByName(phName)
        if ph == 2:
            print ("Please enter the phone number for find:")
            phPhone = raw_input()
            db.findByPhone(phPhone)

1 个答案:

答案 0 :(得分:0)

你有一个Rec列表,它有两个字段,名称和电话。但是您正在搜索该列表是一个可能是电话号码或名称的项目列表(检查子列表是否在列表中,是否是列表中的项目?)。

我认为你在这里犯了错误:

   for el in self.list:
        if substr in self.list:
            res.append(el)

为什么要遍历列表中的所有项目,然后为每个项目忽略它(!)并检查substr是否在self.list中?如果您正在检查substr是否在self.list中(我认为这里不正确),那么您不需要循环。如果你正在循环,那么对于self.list中的每个el,你想要用el做一些事情。

也许你的意思是:

   for el in self.list:
        if substr in el:
            res.append(el)

但我认为这不起作用。

在我看来,你需要单独的手机和名字功能。对于手机,你会有:

   for el in self.list:
        if substr == el.name:
            res.append(el)

同样适用于手机。