1

我有一个名为“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")

任何输入表示赞赏,谢谢。

4

2 回答 2

2

您可以使用del通过索引直接从列表中就地删除元素。
请注意,我以相反的顺序迭代位置,否则在删除剩余索引后,所有位置都会发生变化。

for each_index_positions, each_candidate_keywords in zip(
    positions_to_remove_all, candidate_keywords_all
):
    for pos in reversed(each_index_positions):
        del each_candidate_keywords[pos]
于 2020-07-28T12:49:50.123 回答
1

在所有情况下,您都必须遍历您的列表。因此,您无法在此处获得任何性能,但如果您担心行数,则可以使用单个列表理解来编写它:

final_keywords = [[item for j, item in enumerate(sublist) if j not in positions_to_remove_all[i]]
                  for i, sublist in enumerate(candidate_keywords_all)]
于 2020-07-28T12:56:05.410 回答