如何通过循环自动生成故事片段对应的独立列表?
自动生成独立列表的解决方案
一、为每个语句片段生成独立列表
如果要给拆分后的每个语句片段自动创建独立列表,无需手动定义变量,可以用字典来存储这些列表,通过循环动态生成键名和对应的列表:
en_story = """It was a dark and moonless night. Enough light shone from the porch light to show the broken coat hanger that stuck out of the porch stair rail. Lily sighed and wrapped her shawl around her other arm, picking her way from the driveway to the porch. She had known this day would come. It was inevitable, really. First her car had broken down, and then she'd lost her job. And now, here she was, returning to the one place she had sworn she would never set foot in again. The key turned in the lock with a click, and Lily stepped into the musty-smelling house. It wasn't much, but it was home. She flicked on the light, revealing a dusty living room with peeling wallpaper and a sagging couch. Lily sighed and dropped her bags on the floor. It was going to be a long night.""" # 预处理:拆分语句并去除空内容和多余空格 en_sentence = [s.strip() for s in en_story.split(".") if s.strip()] # 用字典动态存储每个片段的独立列表 sentence_lists = {} for idx, sentence in enumerate(en_sentence, start=1): # 按序号命名列表,比如sentence_1、sentence_2 sentence_lists[f"sentence_{idx}"] = [sentence] # 查看生成的所有列表 for list_name, content in sentence_lists.items(): print(f"{list_name}: {content}")
运行后会自动生成对应每个语句的列表,比如sentence_1对应第一个语句的列表,无需手动逐个定义变量。
二、按规则自动生成分类列表(如good/bad)
如果需要像示例中那样按规则分类生成列表,同样可以用字典先定义分类规则,再自动创建对应列表,避免手动初始化good、bad这类变量:
# 先定义分类规则:键是列表名,值是判断条件的函数 category_rules = { "good": lambda s: "Lily" in s, # 包含Lily的语句归为good "bad": lambda s: "Lily" not in s # 不包含Lily的语句归为bad } # 自动初始化所有分类列表 category_lists = {cat: [] for cat in category_rules.keys()} # 遍历语句,按规则分配到对应列表 for sentence in en_sentence: for cat, check_rule in category_rules.items(): if check_rule(sentence): category_lists[cat].append(sentence) # 打印分类结果 for cat, lst in category_lists.items(): print(f"{cat}: {lst}")
这种方式的优势是:如果后续需要增加新的分类,只需在category_rules里添加新的键和规则即可,无需修改列表初始化的代码。
修正原代码的逻辑问题
原示例中good/bad的判断逻辑存在问题:i_set = set(i),而item本身就在i里,所以所有元素都会被加入good,bad始终为空。上面的代码通过明确的分类规则(比如是否包含特定关键词)解决了这个问题。
内容的提问来源于stack exchange,提问作者Rafael Ventura
相关产品推荐
相关产品推荐

