[Tutor] comparing lists of strings with each other
Lloyd Kvam
pythontutor at venix.com
Wed Feb 4 12:37:12 EST 2004
> for key in listTwo:
> if key != list: # this is line is not what you really want
> return list
You really wanted:
if key not in list:
In Python2.3 there is now a sets module. I've been going wild using it in
my unit testing scripts. The sets module makes it VERY easy to convert
lists to Sets and determine the differences between Sets.
jan willem maaskant wrote:
> Hello,
> i have a problem, with comparison of two strings in a list using the filter
> function.
> and i really don't know the solution.
>
> Here is the problem.
>
> i have two lists filled with strings and i want to filter the strings from
> one list out of the other.
>
> for example:
>
> listOne = [ 'a','b','c']
> listTwo = ['a','c']
>
> i want to remove the strings in listOne which are equal to the strings in
> listTwo.
> So the list i want to have must look like this.
>
> listThree = ['b']
>
> i tried it with the following code:
>
>
>>>>def removeStrings(list):
>
> for key in listTwo:
> if key != list:
> return list
>
>
>
>>>>listThree = filter(removeStrings, listOne)
>
> however this results in
>
>>>>listThree
>
> ['a', 'b', 'c']
>
>
> so this is wrong, but what i really don't understand, is why the opposite
> seems to work quite fine
> if I put this code in
>
>
>>>>def removeStrings(list):
>
> for key in listTwo:
> if key == list: # i changed the comparison operator
> return list
>
> than the function gives exactly what i expected:
>
>
>>>>listThree = filter(removeStrings, listOne)
>>>>listThree
>
> ['a', 'c']
>
> So i'm obviously missing something here, but i'm out of solutions and i am
> not able to find it in any of my books.
> I would be very much helped if somebody could explain this to me
>
> jan willem maaskant
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 801-459-9582
More information about the Tutor
mailing list