comparing lists
Mark McEahern
mark at mceahern.com
Wed May 8 17:40:26 EDT 2002
Suppose I want to do a boolean comparison (equal or not equal) of two lists
case-insensitively and I don't care about order. I can do this:
1. Create temporary copies that are lowercased and use the in operator:
2. Sort temporary copies, then then compare them.
Are there other options? Is there a strong reason to prefer one approach
over the other?
Sample code below.
Thanks,
// mark
#! /usr/bin/env python
l = ['a', 'b', 'c']
m = ['C', 'B', 'A']
def lower(l):
return [x.lower() for x in l]
def compare_with_in(l, m):
assert(len(l) == len(m))
t1 = lower(l)
t2 = lower(m)
for x in t1:
assert(x in t2)
def compare_with_equals(l, m):
t1 = lower(l)
t2 = lower(m)
t1.sort()
t2.sort()
assert(t1==t2)
compare_with_in(l, m)
compare_with_equals(l, m)
More information about the Python-list
mailing list