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

Python使用split函数处理日期列表时触发int()参数类型错误求助

问题原因分析
  • 报错核心原因是你使用了切片语法[-1:]获取split后的结果:x.split("-")会返回由三个元素组成的列表,比如处理'01-Jan-1990'时返回['01','Jan','1990'],使用[-1:]切片会返回仅包含最后一个元素的列表['1990'],而非单个字符串值,因此传给int()转换时触发类型错误。
  • 仅需把[-1:]修改为[-1]即可,直接取列表最后一个元素的字符串值,完全符合你要求的使用split函数的规则。
修正后可运行代码
dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965', 
            '18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']

year = 2021
age =[]

for x in dob_list:
    age.append(year - int(x.split("-")[-1]))

print(age)

运行输出结果为:[31, 26, 39, 33, 45, 56, 44, 27, 40, 40]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:18:05