【问题标题】:how to compare contents at every index of two arrays and return the matching index如何比较两个数组的每个索引处的内容并返回匹配的索引
【发布时间】:2017-08-24 13:16:29
【问题描述】:

我需要比较两个数组,其中一个数组的值存在于另一个数组中,我需要在另一个数组中匹配后插入下一个位置。但在我的代码中它什么也没做。

这是我的代码:

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

【问题讨论】:

  • results 是一个空列表,它不包含任何内容
  • 数据示例非常有用。将整个数组 result 与数组 words 的元素进行比较,但如果没有您正在使用的数据示例,则无法知道。
  • @N.Ivanov 结果不为空..我需要结果中存在的匹配值的下一个索引值
  • 我发表评论的时候,好像你已经更新了答案
  • @N.Ivanov 你能帮我解决这个问题吗?

标签: python arrays string list


【解决方案1】:

根据您的评论

我想将结果列表的每个值与单词列表匹配。如果找到匹配项,那么我想将该值添加到新数组中。

有一个非常简单的方法可以做到这一点。这是一个工作示例:

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']

希望这会有所帮助!

【讨论】:

  • 它给了我一个空数组。
  • @Nisa 我只是复制粘贴并运行它。工作没有问题。我不确定它如何不适合你。我正在使用 Python 2.7。尝试复制粘贴解决方案,看看您是否遗漏了什么。否则程序运行没有问题。
  • 你能帮忙解决这个问题吗? stackoverflow.com/questions/45881148/…
  • @Nisa 你坐下,看看一些教程,自己学习并解决它怎么样? SO 不是免费的编码服务,也不是教程网站。
【解决方案2】:

根据评论

我想将结果列表的每个值与单词列表匹配。如果找到匹配项,那么我想将该值添加到新数组中。

这是另一种方法

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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
  • 2016-12-23
  • 2012-05-09
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多