简体   繁体   中英

Python: find exact word in list

Set-up

I have the following dictionary,

d={'City':['Paris', 'Berlin','Rome', 'London']}

and the following one-element list,

 address=['Bedford Road, London NW7']   


Problem

I want to check if one of the cities is in the address.


Tried so far

(1)

 for x in d['City']: if x in address: print('yes') else: print('no') 

only prints no .

(2)

 for x in d['City']: r = re.compile(x) newlist = list(filter(r.match, address)) 

gives a TypeError: 'str' object is not callable . Got this one from this answer which seems to be what should solve this, but the error doesn't help.

How do I go about?

Your solution #1 was actually quite close, but it doesn't work, because address is a list of string, not a string itself.

So, it will work perfectly fine, if you just take first element of list address ie address[0] .

Alternatively, you can try this:

>>> any(i in address[0] for i in d['City'] )
True

For code snippet, you can use:

if any(i in address[0] for i in d['City'] ):
    print 'Yes'
else:
    print 'No'

Since your address is a one-element list, you should check address[0] instead of address :

for x in d['City']:
    if x in address[0]:
        print('yes')
    else:
        print('no')

If you aren't increasing the size of the list:

for x in d['City']:
    if x in address[0]:
        print('yes')
    else: 
        print('no')

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