Python for循环报错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

