0

I found code to find the similarities (or differences) of lists on this page: How can I compare two lists in python and return matches

>>> set(a).intersection(b)
set([5])

However, it's not working when I compare a list I made to a list made by reading a file like so:

myvalues = ['a1', '2b', '3c']    # same values found in values.txt, line by line 

with open('values.txt', 'r') as f:
    filevalues = f.readlines()

for line in filevalues:
    line = line.strip()

matches = set(myvalues).intersection(filevalues)
print matches

output: 
set([])

It DOES work on two slightly different lists I made in the script itself, and DOES work when I compare the filevalues to filevalues. Not sure what I'm missing but I'm guessing the problem has something to do with the types or format of the list that is created by reading the file's lines.

Anyone know how to go about troubleshooting this?

1
  • You need to indent the body of with. Commented Dec 18, 2015 at 21:41

1 Answer 1

3

The elements of f.readlines() will be terminated with a \n character, that is why you are getting zero matches.

In response to the comment:

That's what I thought, but I'm even doing this before the comparison: for line in filevalues: line = line.strip()

Your loop does nothing to the lines in filevalues. Use

filevalues = [x.strip() for x in filevalues]
Sign up to request clarification or add additional context in comments.

4 Comments

That's what I thought, but I'm even doing this before the comparison: for line in filevalues: line = line.strip()
@Thisisstackoverflow: but that won't change the values in filevalues. That just says "for every element in filevalues, strip it and give that new element the name 'line'".
@Thisisstackoverflow your loop does nothing to the lines in filevalues. Use filevalues = [x.strip() for x in filevalues].
set(myvalues).intersection(itertools.imap(str.rstrip,f))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.