[Tutor] comparing lists of strings with each other
Lloyd Kvam
pythontutor at venix.com
Wed Feb 4 12:56:20 EST 2004
Good thing you are watching Rich. I scanned right past the use
of filter. The variable name "list" convinced me I was looking
at a list. (Actually list is also a bad choice for variable name
because it hides the builtin list.)
Rich Krauter wrote:
> If you trace out each step of what filter is doing,
> you'll see why you are getting what you are getting.
>
> By using filter, you are passing each element of the
> first list into your comparison function. Your
> comparison function compares the passed-in item with
> each item in the second list, and returns the item (a
> true value) when the two are not equal:
>
> 'a' in list1 != 'c' in list2, so 'a' is returned
> 'b' in list1 != 'a' in list2, so 'b' is returned
> 'c' in list1 != 'a' in list2, so 'c' is returned
>
> Filter is documented here:
> http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26
>
> You can do this without filter, using list membership
> tests:
>
>>>>newlist = []
>>>>for x in list1:
>
> ... if x not in list2:
> ... newlist.append(x)
>
> or
>
>
>>>>f = lambda i: i not in list2
>>>>filter(f,list1)
>>>>['b']
>
>
> One way you can do what you want in python 2.3 is with
> sets:
>
>>>>import sets
>>>>a1 = ['a','b','c']
>>>>a2 = ['a','c']
>>>>s1 = sets.Set(a1)
>>>>s2 = sets.Set(a2)
>
>
> #find all elements of s1 not in s2
>
>>>>list(s1-s2)
>
> ['b']
>
> Rich
>
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free web site building tool. Try it!
> http://webhosting.yahoo.com/ps/sb/
>
> _______________________________________________
> 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