comparing lists

Delaney, Timothy tdelaney at avaya.com
Wed May 8 20:44:22 EDT 2002


> From: Lulu of the Lotus-Eaters [mailto:mertz at gnosis.cx]
> 
> You can always sort the lists before joining them.  Or sort copies if
> you need to leave the originals as-s.  I.e.
>
>     ltmp = copy.copy(lst)
>     ltmp.sort()
>
>     l1 = ['ab ','c',' d']
>     l2 = ['ab',' c ','d']
>     l3 = ['ab  c  d']

That won't work - you need to perform the case-conversion before the sort.

> These will all compare as equal.  What you probably want to 
> do is add a
> delimiter between the elements that you are pretty sure will not occur
                                              ^^^^^^^^^^^
> in the original strings, e.g.:
> 
>     >>> string.join(['a','b','c'],'$%^').upper()
>     'A$%^B$%^C'
> 
> or,
> 
>     >>> '|-|'.join(['a','b','c']).upper()
>     'A|-|B|-|C'

Make that 100% certain will not occur in the original strings ...

I would suggest just sticking with converting to lowercase, sorting, then
comparing.

l1 = ['a', 'b', 'c']          # or any iterable
l2 = ['C', 'a', 'B']          # or any iterable

l1 = map(string.lower, l1)    # or l1 = [x.lower() for x in l1]
l2 = map(string.lower, l2)    # or l2 = [x.lower() for x in l2]

l1.sort()
l2.sort()

assert(l1 == l2)

Tim Delaney





More information about the Python-list mailing list