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

Python实现接收二维列表的printAgeDiff函数输出相邻人员年龄差

printAgeDiff 函数实现方案

核心逻辑

  • 遍历相邻人员对:通过 range(len(table)-1) 生成遍历索引,每次取索引 i 和 i+1 对应的两组人员数据
  • 切片传参解决你的问题:每个人员子列表从索引2开始的元素正好是出生年、月、日,用 person[2:] 即可切片取出这三个值,再通过 * 解包直接传入你已经写好的 findAge 函数,不需要手动逐个提取参数
  • 比对两人年龄后按照要求拼接字符串输出即可

完整代码示例

def printAgeDiff(table):
    # 遍历所有相邻人员组合
    for i in range(len(table) - 1):
        current_person = table[i]
        next_person = table[i + 1]
        # 切片获取出生日期,解包传入findAge计算年龄
        current_age = findAge(*current_person[2:])
        next_age = findAge(*next_person[2:])
        # 拼接两人全名
        current_fullname = f"{current_person[0]} {current_person[1]}"
        next_fullname = f"{next_person[0]} {next_person[1]}"
        # 按年龄比对结果输出
        if current_age == next_age:
            print(f"{current_fullname} is at the same age as {next_fullname}")
        elif current_age > next_age:
            print(f"{current_fullname} is older than {next_fullname}")
        else:
            print(f"{current_fullname} is younger than {next_fullname}")

# 测试用findAge示例,可替换为你自己实现的版本
def findAge(year, month, day):
    from datetime import date
    today = date.today()
    age = today.year - year
    if (today.month, today.day) < (month, day):
        age -= 1
    return age

# 调用测试
table=[['Justin','Bieber',1994,3,1],
   ['Donald','Duck',1934,8,1],
   ['George','Clooney',1961,5,6],
   ['Eddie','Murphy',1961,4,3]]
printAgeDiff(table)

输出结果

和题目要求的示例完全一致:

Justin Bieber is younger than Donald Duck
Donald Duck is older than George Clooney
George Clooney is at the same age as Eddie Murphy

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:24:07