You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表中基于姓名的Linear Search实现问题求助

线性搜索用户数据的问题解决

问题概述

需要在存储用户数据的列表中使用线性搜索,通过名字(firstname)和姓氏(lastname)查找用户并输出其余信息,目前代码存在三个问题:

  • 无法找到列表中的"Bob"
  • 不知道如何同时匹配firstname和lastname
  • 找到对象后打印的是对象本身而非用户数据

问题解决与代码修改

1. 解决无法匹配用户的问题

原代码直接用arr[i] == T比较对象和字符串,这是错误的——你需要比较对象的childfirstname属性和目标字符串,而非对象本身。

2. 实现同时匹配firstname和lastname

修改搜索函数,让它接收目标名字和姓氏两个参数,循环中同时判断对象的childfirstname和childlastname是否与目标匹配。

3. 打印用户的具体数据

推荐给child类添加__str__方法,自定义对象被打印时的输出格式,这样直接打印对象就能得到格式化的用户数据,代码更简洁。


修改后的完整代码

# Create Child Class
class child:
    def __init__(self, childfirstname, childlastname, childdob, childgender, childyearlvl, childethnicity):
            self.childfirstname = childfirstname
            self.childlastname = childlastname
            self.childdob = childdob
            self.childgender = childgender
            self.childyearlvl = childyearlvl
            self.childethnicity = childethnicity
    
    # 添加__str__方法,自定义对象打印内容
    def __str__(self):
        return f"{self.childfirstname}  {self.childlastname}  {self.childdob}  {self.childgender}  {self.childyearlvl}  {self.childethnicity}"
  
# Create list to allow for Sequential Search
childlist = []
childlist.append(child('Bob','Jones','101015','Male','8','European'))
childlist.append(child('Sally','Fail','200115','Female','8','Maori'))

# Testing output of values stored in childlist
for obj in childlist: 
  print(obj)

print("")

# Sequential search - 同时接收名字和姓氏参数
def search(arr, target_first, target_last):
    n = len(arr)
    for i in range(n):
        # 同时匹配名字和姓氏
        if arr[i].childfirstname == target_first and arr[i].childlastname == target_last:
            return i
    return -1

# 测试搜索Bob Jones
result = search(childlist, 'Bob', 'Jones')
if result != -1:
  print("Child found: ", childlist[result])
else:
  print("Child not found")

# 测试搜索不存在的用户
result = search(childlist, 'John', 'Doe')
if result != -1:
  print("Child found: ", childlist[result])
else:
  print("Child not found")

代码说明

  • __str__方法:定义了对象被打印时的输出格式,和你之前测试循环打印的格式一致
  • search函数:现在接收target_first和target_last两个参数,循环中同时判断两个属性是否匹配
  • 调用搜索时,需要传入完整的名字和姓氏,确保精确匹配

内容的提问来源于stack exchange,提问作者Ethan Cunningham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:50:42