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

如何使用循环将列表中季数从字符串转为整数并替换原位置

将列表中的季数字符串转换为整数

原始数据

shows = [
["The Imperfects", "Science Fiction", "1", "entertaining"],
["Devil in Ohio", "Thriller", "1", "spooky"],
["The Crown", "Historical Drama", "4", "Powerful"],
["Narco-Saints", "Thriller", "1", "Entertaining"],
["In the Dark", "Crime Drama", "4", "intriguing"]]

方法1:直接遍历子列表修改

Python列表属于可变对象,遍历每个子列表时直接修改对应位置的元素,改动会同步到原列表中:

for show in shows:
    # 第三个元素的索引为2(从0开始计数),转成整数后替换原位置
    show[2] = int(show[2])

方法2:通过索引遍历修改

如果需要跟踪每个元素的位置,可以用索引遍历的方式:

for i in range(len(shows)):
    shows[i][2] = int(shows[i][2])

验证结果

执行上述任意一段代码后,打印shows即可看到季数已转为整数类型:

print(shows)
# 输出:
# [["The Imperfects", "Science Fiction", 1, "entertaining"],
#  ["Devil in Ohio", "Thriller", 1, "spooky"],
#  ["The Crown", "Historical Drama", 4, "Powerful"],
#  ["Narco-Saints", "Thriller", 1, "Entertaining"],
#  ["In the Dark", "Crime Drama", 4, "intriguing"]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:30:53