如何根据python列表中对象的相对列表位置来比较它们?
我有一些文本数据,我正试图清理。此数据的一个不需要的特性是由特定标记分隔的重复标记。我试图找到一种方法来(1)识别文本中的标记,以及(2)删除其中一个重复的标记 玩具示例:如何根据python列表中对象的相对列表位置来比较它们?,python,list,text,Python,List,Text,我有一些文本数据,我正试图清理。此数据的一个不需要的特性是由特定标记分隔的重复标记。我试图找到一种方法来(1)识别文本中的标记,以及(2)删除其中一个重复的标记 玩具示例: word_list = ['this','is','a','!!','a','list','I','want','to','clean'] 这里有两个重复的“a”标记,由标记“!!”分隔。我正试图找到一种最有效的方法,用下面的代码遍历这个列表 #pseudo for word in word_list if wor
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']
我已经尝试了几种涉及
枚举
函数的方法,但似乎无法使其正常工作。以下几点可以奏效:
word_list = ['this','is','a','!!','a','list','I','want','to','clean']
i, marker, output = 0, "!!", []
while i < len(word_list):
x = word_list[i]
output.append(x)
if word_list[i+1:i+3] == [marker, x]:
i += 3
else:
i += 1
output
# ['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']
result=[]
for i in range(len(word_list)-2):
if not (word_list[i]=='!!' or (word_list[i+1]=='!!' and word_list[i+2]==word_list[i])):
result.append(word_list[i])
if word_list[-2]!='!!':
result.append(word_list[-2])
if word_list[-1]!='!!':
result.append(word_list[-1])
print(result)
#['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']
使用您的逻辑和
枚举
功能:
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']
这将有助于:
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]: # checking if they are duplicates
del word_list[i+1] # removing the duplicate
del word_list[i] # removing the marker
我知道你的分隔符总是“!!”!!“以下各项应起作用:
word_list = ['this','is','a','!!','a','list','I','want','to','clean']
i, marker, output = 0, "!!", []
while i < len(word_list):
x = word_list[i]
output.append(x)
if word_list[i+1:i+3] == [marker, x]:
i += 3
else:
i += 1
output
# ['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']
result=[]
for i in range(len(word_list)-2):
if not (word_list[i]=='!!' or (word_list[i+1]=='!!' and word_list[i+2]==word_list[i])):
result.append(word_list[i])
if word_list[-2]!='!!':
result.append(word_list[-2])
if word_list[-1]!='!!':
result.append(word_list[-1])
print(result)
#['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']
请解释一下。