如何访问Python嵌套列表的单个值?最优遍历取值及报错解决方法是什么?
问题解决
错误原因
你写的嵌套循环逻辑有误:
你定义的List外层是仅包含1个字典元素的列表,第一层循环for anime in list取出的anime就是这个字典对象。第二层循环for show in anime默认遍历字典的键,得到的show是'name'、'poster'、'summary'这类字符串,你用字符串去做show["name"]的索引操作,自然会抛出TypeError: string indices must be integers的报错。
打印所有name值的实现代码
# 先取出列表中的唯一字典元素,再获取key为name对应的列表 name_list = List[0]['name'] # 遍历打印每个name值 for name in name_list: print(name)
注:你给出的原始数据中
poster字段的"flyer 6"后缺失逗号,运行前需要先补全避免语法报错。
传递数据到HTML页面展示
以常用的Flask框架为例,实现逻辑如下:
后端代码
from flask import Flask, render_template app = Flask(__name__) # 你的动画数据 AnimeList = [{ 'name': ['NARUTO×UT', 'Naruto, the Genie, and the Three Wishes, Believe It!', 'Naruto SD: Rock Lee no Seishun Full-Power Ninden Mō Iccho', 'Naruto Shippūden: The Burning Chūnin Exam! Naruto vs. Konohamaru!!', 'Naruto: The Cross Roads', 'Naruto Spin-Off: Rock Lee & His Ninja Pals', 'Naruto Shippūden: Shippū! "Konoha Gakuen" Den', 'Naruto Shippūden: Blood Prison', 'Naruto Shippūden: The Lost Tower', 'Naruto Shippūden: The Will of Fire', 'Naruto Shippūden the Movie: Bonds', 'Naruto Shippūden', 'Naruto: Konoha Sports Festival', 'Naruto Shippūden', 'Naruto the Movie: Guardians of the Crescent Moon Kingdom', 'Naruto', 'Naruto the Movie: Legend of the Stone of Gelel', 'Naruto Special: Battle at Hidden Falls. I Am the Hero!', 'Naruto: Akaki Yotsuba no Clover o Sagase', 'Naruto the Movie: Ninja Clash in the Land of Snow', 'Naruto'], 'poster': ["flyer 1","flyer 2", "flyer 3", "flyer 4", "flyer 5","flyer 6", "flyer 7", "flyer 8", "flyer 9", "flyer 10", "flyer 11", "flyer 12", "flyer 13", "flyer 14"], 'summary': ["plot 1", "plot 2", "plot 3", "plot 4", "plot 5", "plot 6", "plot 7", "plot 8","plot 9", "plot 10", "plot 11", "plot 12","plot 13", "plot 14", ] }] @app.route('/anime') def show_anime(): # 提取数据传递到HTML模板 anime_data = AnimeList[0] return render_template('anime.html', anime_data=anime_data) if __name__ == '__main__': app.run(debug=True)
HTML模板代码(路径为templates/anime.html)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>动画列表</title> <style> .anime-item {margin: 20px 0; padding-bottom: 15px; border-bottom: 1px solid #eee;} img {max-width: 200px;} </style> </head> <body> <h1>火影相关动画作品</h1> <div class="anime-container"> {% for name, poster, summary in zip(anime_data['name'], anime_data['poster'], anime_data['summary']) %} <div class="anime-item"> <h3>{{ name }}</h3> <img src="{{ poster }}" alt="{{ name }}海报"> <p><strong>剧情简介:</strong>{{ summary }}</p> </div> {% endfor %} </div> </body> </html>
如果使用Django框架,只需要在后端将三个字段按索引打包成嵌套列表再传递到模板,直接遍历嵌套列表即可,模板语法和上述逻辑一致。
内容的提问来源于stack exchange,提问作者Drey's
相关产品推荐
相关产品推荐

