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

Python for循环报错TypeError:列表索引需为整数而非元组的解决方法

解决遍历元组列表时的TypeError问题

你遇到的问题很典型——在for i in link_list循环里,i并不是你以为的列表索引,而是列表里的每一个元组元素!所以当你写link_list[i][0]的时候,相当于用一个元组去当列表的索引,这就触发了TypeError: list indices must be integers, not tuple的错误。

看一下你的link_list结构,每个元素都是包含路径字符串和日期的元组,那我们直接遍历每个元组,取出第一个元素就好啦:

正确代码示例

base_url = 'http://www.newyorksocialdiary.com'
for item in link_list:
    print(f"{base_url}{item[0]}")

或者用你原来的字符串格式化写法也可以:

for item in link_list:
    print('http://www.newyorksocialdiary.com%s' % item[0])

运行后会输出:

http://www.newyorksocialdiary.com/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up
http://www.newyorksocialdiary.com/party-pictures/2014/gala-guests
http://www.newyorksocialdiary.com/party-pictures/2014/equal-justice
http://www.newyorksocialdiary.com/party-pictures/2014/celebrating-the-treasures
http://www.newyorksocialdiary.com/party-pictures/2014/associates-and-friends

简单来说,你之前混淆了遍历列表元素和遍历索引的写法。如果以后确实需要索引的话,可以用for idx, item in enumerate(link_list),但这里完全不需要,直接遍历每个元组就够啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:36:51