如何在Python中依据分数列表筛选句子生成新列表?
问题分析与解决
你的代码问题出在遍历scores时直接用元素值作为sentences的索引,而不是用索引去匹配scores和sentences的对应位置。比如scores里的第一个1,对应的是sentences的第0个元素,而不是sentences[1]。
修正后的for循环版代码
sentences = ['The house is big','Look at the tree','He is eating food'] scores = [1,0,1] newlist = [] # 用enumerate同时获取索引和分数值 for idx, score in enumerate(scores): if score == 1: newlist.append(sentences[idx]) print(newlist)
更简洁的列表推导式版
sentences = ['The house is big','Look at the tree','He is eating food'] scores = [1,0,1] newlist = [sentences[idx] for idx, score in enumerate(scores) if score == 1] print(newlist)
原代码错误原因
原循环遍历的是scores里的数值(1、0、1),当i=1时,你取的是sentences[1](即第二个句子),最终得到的是['Look at the tree', 'Look at the tree'],完全不符合预期。而用enumerate可以拿到每个分数对应的位置索引,这样就能准确匹配到sentences里对应的句子。
内容的提问来源于stack exchange,提问作者Brady Monks
相关产品推荐
相关产品推荐

