[英]How to compare objects in a python list based on their relative list position?
我有一些要清理的文本數據。 該數據的一個不良特征是由特定標記分隔的重復標記。 我正在嘗試找到一種方法來 (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
function 的方法,但似乎無法使其正常工作。
使用您的邏輯和enumerate
function:
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])
Output:
['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
我你的分隔符總是 ':!" 以下應該可以工作:
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']
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']
如果你想改變原始列表 object:
word_list[:] = output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.