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?

Community
  • 1
  • 1
Thisisstackoverflow
  • 251
  • 1
  • 2
  • 11

1 Answers1

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]
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • That's what I thought, but I'm even doing this before the comparison: for line in filevalues: line = line.strip() – Thisisstackoverflow Dec 18 '15 at 21:42
  • 1
    @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'". – DSM Dec 18 '15 at 21:43
  • @Thisisstackoverflow your loop does nothing to the lines in `filevalues`. Use `filevalues = [x.strip() for x in filevalues]`. – timgeb Dec 18 '15 at 21:43
  • `set(myvalues).intersection(itertools.imap(str.rstrip,f))` – Padraic Cunningham Dec 18 '15 at 21:46