Pumpkin C
Pumpkin C

Reputation: 1492

return word if the word is in a list string

I want to return the city in my address column, if the city is in my list_cities.

Cities = ['Los Angeles','New York']
Address = ['New York 123 ave unit 804','Los Angeles 567 ave unit 701']

if any(city in address for city in Cities):
    print ()

I want a return of ['New York','Los Angeles'], is there any way i can do this? Thank you!

Upvotes: 0

Views: 41

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can iterate over Cities instead:

Cities = ['Los Angeles','New York']
Address = ['New York 123 ave unit 804','Los Angeles 567 ave unit 701']
final_cities = [i for i in Cities if any(i in b for b in Address)]

For a solution sorted based on position in Address:

new_Address = {a:[c for c, d in enumerate(Address) if a in d] for a in Cities}
final_address = map(lambda x:x[0], sorted({a:b for a, b in new_Address.items() if b}.items(), key=lambda x:x[-1]))

Output:

['New York', 'Los Angeles']

Upvotes: 3

Related Questions