[英]compare two lists (python)
I need to compare two lists in a program to see if there are matching strings.我需要比较程序中的两个列表以查看是否有匹配的字符串。 One of them is a txt document that I already imported.
其中之一是我已经导入的 txt 文档。 Thats what I did
这就是我所做的
def compareLists(self, listA, listB):
sameWords = list()
for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
if listA[a] == listB[b]:
sameWords.append(listA[a])
pass
pass
pass
return sameWords
But if I run the program it doesnt show any matches although I know that there has to be one.但是,如果我运行该程序,它不会显示任何匹配项,尽管我知道必须存在匹配项。 I think its somewhere inside the if block.
我认为它在 if 块内的某个地方。
I am assuming the indentation is correct in your code.我假设您的代码中的缩进是正确的。 Continuing with your strategy, this code should work.
继续你的策略,这段代码应该可以工作。
def compareLists(self, listA, listB):
sameWords = list()
for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
if listA[a] == listB[b]:
sameWords.append(listA[a])
return sameWords
Alternatively, as @Efferalgan suggested, simply do the set intersection.或者,正如@Efferalgan 建议的那样,只需进行设置交集。
def compareLists(self, listA, listB):
return list(set(listA) & set(listB))
Note: The set intersection will remove duplicate matching words from your result.注意:设置的交集将从您的结果中删除重复的匹配词。
As you said, you are reading in the lines from a text file, and it looks like the newlines are still in there.正如您所说,您正在读取文本文件中的行,看起来换行符仍在那里。
my_text_list = [s for s in open("my_text.txt").read().rsplit()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.