如何从列表子集中随机取值?动漫生成器开发问题
按动漫类型筛选并随机推荐动漫
完整实现代码
import random anime_list = [ ['Fullmetal Alchemist: Brotherhood', 'Action', 'Fantasy'], ['Mob Psycho 100', 'Action', 'Comedy'], ['Kill la Kill', 'Action', 'Comedy'], ['Spy x Family', 'Action', 'Comedy'], ['Black Lagoon', 'Action'] ] print('What genre do you want to watch?') genre = input().strip() # 去除输入前后空格,提升匹配容错率 # 筛选包含指定类型的动漫 filtered_animes = [anime for anime in anime_list if genre in anime] if filtered_animes: selected_anime = random.choice(filtered_animes) print(f"推荐动漫:{selected_anime[0]}(类型:{', '.join(selected_anime[1:])})") else: print(f"未找到包含「{genre}」类型的动漫,请更换类型重试!")
关键步骤说明
类型筛选逻辑
你猜测需要用for循环是对的,上面的列表推导式本质是简化的循环写法。如果要更直观的循环实现,代码如下:filtered_animes = [] for anime in anime_list: # 检查当前动漫的类型列表中是否包含用户输入的类型 if genre in anime: filtered_animes.append(anime)这段代码会遍历所有动漫,把符合类型要求的项存入
filtered_animes列表。随机选取与异常处理
用random.choice()从筛选后的列表中随机选一项即可。必须先判断filtered_animes是否为空——如果用户输入了不存在的类型(比如Romance),直接调用random.choice()会抛出错误,所以加个判断分支提示用户。输入优化
用strip()处理用户输入,避免因为误输入空格导致匹配失败(比如用户输入Comedy也能正确匹配Comedy)。
内容的提问来源于stack exchange,提问作者kthzs
相关产品推荐
相关产品推荐

