简体   繁体   中英

search list for exact match

How can I search list(s) where all the elements exactly match what I'm looking for. For instance, I want to verify if the following list consist of 'a', 'b' and 'c', and nothing more or less.

lst=['a', 'b', 'c']

I did this:

if 'a' in lst and 'b' in lst and 'c' in lst:
   #do something

Many thanks in advance.

You can sort the lists and then simply compare them: sorted( list_one ) == sorted( list_two ) .

Also you can convert both lists to sets and compare them. But be careful, sets eat duplicate items! set( list_one ) == set( list_two ) .

Sets can also tell you which items either set is lacking: set(list_one) ^ set(list_two) .

Some examples:

>>> sorted("asd") == sorted("dsa")
True
>>> sorted( "asd" ) == sorted( "dsa" )
True
>>> sorted( "asd" ) == sorted( "dsaf" )
False
>>> set( "asd" ) == set( "dasf" )
False
>>> set( "asd" ) == set( "daas" )
True
>>> set( "asd" ) ^ set( "daf" )
set(['s', 'f'])

This does actually work. Why do you think it doesn't?

Also, are you aware of Python sets? http://docs.python.org/library/sets.html

Using sets is fine for what has been asked: In the first case, the lists are identical, having all the elements, nothing less or more While in the second case it is not and it shows up. You can use this for this purpose.

>>> lst=['a', 'b', 'c']
>>> listtocheck = ['a', 'b', 'c']
>>> s1 = set(lst)
>>> s2 = set(listtocheck)
>>> k = s1 ^ s2
>>> k
set([])
>>> listtocheck = ['a', 'b', 'c', 'd']
>>> s2 = set(listtocheck)
>>> k = s1 ^ s2
>>> k
set(['d'])
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM