Python新手求助:如何筛选首元素含the的元组生成新列表
问题分析与修正
你的代码存在几个关键问题:
- 元组是不可变类型,
target_bigrams = ()初始化后无法使用append方法,得换成列表[] - 用
range(bigrams_length)循环得到的i是索引数字,不是元组元素,直接遍历bigrams里的元素更直观 - 判断逻辑错误:你要筛选首元素包含"the"的元组,不是等于未定义的
target_word,而且目标是存入整个元组,不是只存首元素
修正后的代码:
bigrams = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')] target_bigrams = [] # 用列表初始化,支持append操作 for elem in bigrams: # 判断元组第一个元素是否包含"the" if 'the' in elem[0]: target_bigrams.append(elem) # 存入整个符合条件的元组 print(target_bigrams)
运行结果:[('the, this is me', 'the night'), ('the night', 'me')]
也可以用更简洁的列表推导式实现:
bigrams = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')] target_bigrams = [elem for elem in bigrams if 'the' in elem[0]]
内容的提问来源于stack exchange,提问作者pythonhelp
相关产品推荐
相关产品推荐

