Python:返回每个匹配的列表值

2024-06-08 22:56:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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']

我现在的代码是:

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

Tags: 代码in列表newforpython3placessquare
1条回答
网友
1楼 · 发布于 2024-06-08 22:56:16

您不需要中间列表理解,只需:

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

注意:如果locationstour包含许多项,那么可以先将tour设为set,例如tour = set(tour),从而加快代码速度并降低时间复杂度

相关问题 更多 >