首页 > 解决方案 > 如何根据相对列表位置比较python列表中的对象?

问题描述

我有一些要清理的文本数据。该数据的一个不良特征是由特定标记分隔的重复标记。我正在尝试找到一种方法来 (1) 在文本中识别该标记,以及 (2) 删除其中一个重复项。

玩具示例:

word_list = ['this','is','a','!!','a','list','I','want','to','clean']

在这里,有两个重复的 'a' 标记,由标记 '!!' 分隔。我正在尝试使用以下方法找到最有效的方法来遍历列表

#pseudo
for word in word_list
    if word == "!!":
        if word[at word-1] == word[at word+1]  # compare words either side of the "!!" marker
            del word[at word+1]                # removing the duplicate
            del word                           # removing the "!!" marker


output = ['this','is','a','list','I','want','to','clean']

我尝试了几种涉及该enumerate功能的方法,但似乎无法使其正常工作。

标签: pythonlisttext

解决方案


使用您的逻辑和enumerate功能:

word_list = ['this','is','a','!!','a','list','I','want','to','clean']

for i, word in enumerate(word_list):
    if word == "!!":
        if word_list[i-1] == word_list[i+1]:
            word_list[i+1] = ""
            word_list[i] = ""

print ([x for x in word_list if x])

输出:

['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']

推荐阅读