我有一个名为“candidate_keywords_all”的列表,其中包含三个内部字符串列表。另一个名为“positions_to_remove_all”的列表具有要删除的单词的索引位置。我下面的代码通过创建一个新的输出列表来做到这一点。有没有办法不使用新列表?如果我使用 pop 方法修改原始列表,每个 pop 都会影响剩余元素的索引位置,它们不再匹配并导致索引错误。请注意,职位的内部列表也可以为空。
candidate_keywords_all =[
['list1_word1', 'list1_word2', 'list1_word3'],
['list2_word1', 'list2_word2', 'list2_word3', 'list2_word4', 'list2_word5', 'list2_word6'],
['list3_word1', 'list3_word2']
]
positions_to_remove_all =[ [0, 2], [1, 3, 5], [] ]
## extract the Selected keywords into new data structure
final_keywords = []
for each_index_positions, each_candidate_keywords in \
zip(positions_to_remove_all, candidate_keywords_all):
temp_arr = [keyword for idx, keyword in enumerate(each_candidate_keywords) if idx not in each_index_positions]
final_keywords.append(temp_arr)
for each_candidate_keywords, each_index_positions, each_final_keywords in zip(candidate_keywords_all, positions_to_remove_all, final_keywords):
print(f"BEFORE = {each_candidate_keywords}\nRemove positions = {each_index_positions}\nAFTER = {each_final_keywords}\n\n")
任何输入表示赞赏,谢谢。