2017-08-23 50 views
0

需要您的帮助。有一个由类对象组成的列表(数组),如何找到列表中的项目(行),例如:手机还是名字?我有一个功能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

缩进需要修复,但这与您陈述的问题无关。在修改缩进之后,你的代码是两个类,但是你如何使用你的函数?我没有提示输入和输出。 – davedwards

回答

0

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

我认为你在这里有一个错误:

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) 

类似的手机。

+0

是的,你说得对,代码: '为EL在self.list: 如果SUBSTR在El: res.append致发光(EL)' 不工作,我得到了一个错误:在findSubStr如果SUBSTR在El:类型错误:类型 '实例' 的说法是没有迭代 如果我使用的代码:在self.list '为EL: 如果SUBSTR在self.list: res.append致发光(EL)' 他们什么搜索!我按你说的做了,它工作!非常感谢你! 非常好,有这样的网站是高度熟练的程序员分享他们的经验和知识! –

+0

很高兴帮助!对我来说也是鼓舞人心的,因为我对Python的兴趣远远超过我工作的其他语言;鼓励我知道我已经学会了一些东西:-) – Basya