我是python 3的新用户,无法从每个匹配的2个列表中返回值。
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)
答案 0 :(得分:2)
您不需要中间列表理解,只需:
new = [i for i in locations if i[0] in tour]
请注意,如果locations
和tour
包含许多项目,那么您可以先tour
set
tour = set(tour)
来加快代码速度并降低时间复杂度,例如{{1 }}