我需要比较两个数组,其中一个数组的值存在于另一个数组中我需要在另一个数组中匹配后插入下一个位置。但在我的代码中,它没有做任何事情。
这是我的代码:
arr=[]
result=['Alphabets','reveals','help','opinions','Allah']
words=['Alif-Laam-Meem','NNP','Alphabets','NNPS','of','IN','the','DT',' Arabic','NNP','language','NN','Allah','NNP','and','CC','to','TO', 'whomever','VB','He','PRP','reveals','VBZ','know','VBP','their','PRP','precise','JJ','meanings','NNS']
j=4
k=0
while j<len(words): #words contain text file contents that is split into words
while k<len(result): #result is another array containing subsets of words of file.
if result==words[j]: # if values of results match with values of words
arr.append(words[j+1]) #add next index of words in arr.
j+=1
print(arr)
else:
continue
答案 0 :(得分:1)
根据您的评论
我希望将结果列表的每个值与单词list匹配。如果找到匹配项,那么我想在新数组中添加该值。
有一种非常简单的方法可以做到这一点。这是一个有效的例子:
arr=[]
result=['Alphabets','reveals','help','opinions','Something']
words=['Alif-Laam-Meem','NNP','Alphabets','NNPS','of','IN','the','DT',' Arabic','NNP','language','NN','Something','NNP','and','CC','to','TO', 'whomever','VB','He','PRP','reveals','VBZ','know','VBP','their','PRP','precise','JJ','meanings','NNS']
for i in result:
if i in words:
arr.append(i)
print arr
这会给你:
['Alphabest', 'reveals', 'Something']
希望这有帮助!
答案 1 :(得分:0)
基于评论
我希望将结果列表的每个值与单词list匹配。如果找到匹配项,那么我想在新数组中添加该值。
这是另一种方法
result=['Alphabets','reveals','help','opinions','Something']
words=['Alif-Laam-Meem','NNP','Alphabets','NNPS','of','IN','the','DT',' Arabic','NNP','language','NN','Something','NNP','and','CC','to','TO', 'whomever','VB','He','PRP','reveals','VBZ','know','VBP','their','PRP','precise','JJ','meanings','NNS']
arr = [ word for word in result if word in words]
print(arr)