Python:返回每个匹配项的列表值
我是Python3的新手,对于每个匹配都很难从两个列表中返回值Python:返回每个匹配项的列表值,python,python-3.x,Python,Python 3.x,我是Python3的新手,对于每个匹配都很难从两个列表中返回值 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'] 我目前的代码
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)
您不需要理解中间列表,只需:
new = [i for i in locations if i[0] in tour]
注意:如果
位置
和巡演
包含许多项目,那么您可以通过先将巡演
设置为集合
,例如巡演=集合(巡演)
美观简洁,从而加快代码速度并降低时间复杂度。谢谢!!我设法用{places:locationcoordinatestuples}将它转换成字典格式-如果我要执行与上面相同的功能,我将如何执行???