2017-08-30 67 views
1

我是python 3的新手,並且無法從每個匹配的2個列表返回值。Python:返回每個匹配列表的值

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

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

我的代碼找到了匹配,但不會返回位置座標。

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

我當前的代碼是:

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

回答

2

你不需要中間列表理解,簡單地說:

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

注意如果locationstour包含很多項目,那麼你可以加快通過首先製作tour a set來降低時間複雜度,例如tour = set(tour)

+0

不錯,簡潔。 – zedfoxus

+0

謝謝!我設法將它與{places:locationcoordinatestuples}的字典格式 - 如果我要做與上面相同的功能,我該如何做? –