Akira Wang
Akira Wang

Reputation: 53

Python: Return the values of a list for each match

I'm new to python 3 and have trouble returning values from 2 lists for each match.

locations = [("ngv", 4, 0), ("town hall", 4, 4),("myhotel",  2, 2), ("parliament", 8, 5.5), ("fed square",  4, 2)]

tour = ["ngv", "fed square", "myhotel"]

My code finds the matches but won't return the location coordinates as well.

['ngv', 'fed square', 'myhotel']

My current code is:

places = [u[0] for u in locations]
new = [i for i in tour if i in places]
print(new)

Upvotes: 1

Views: 103

Answers (1)

Chris_Rands
Chris_Rands

Reputation: 41168

You don't need the intermediate list comprehension, simply:

new = [i for i in locations if i[0] in tour]

Note if locations and tour contain many items then you can speed up your code and reduce time complexity by making tour a set first, such as tour = set(tour)

Upvotes: 2

Related Questions