Python 查找从一个列表到另一个列表的值的索引
使用Python3,我希望以升序遍历第一个列表中的项,并在第二个列表中找到该项的索引,以将其存储到第三个结果列表中 下面是一个工作示例:Python 查找从一个列表到另一个列表的值的索引,python,python-3.x,list,Python,Python 3.x,List,使用Python3,我希望以升序遍历第一个列表中的项,并在第二个列表中找到该项的索引,以将其存储到第三个结果列表中 下面是一个工作示例: list1 = [53, 65, 67, 37, 14, 98, 122, 124, 183] list2 = [0, 14, 37, 53, 65, 67, 98, 122, 124, 183, 199] wanted_output = getWantedOutput(list1, list2) print(wanted_output) >>
list1 = [53, 65, 67, 37, 14, 98, 122, 124, 183]
list2 = [0, 14, 37, 53, 65, 67, 98, 122, 124, 183, 199]
wanted_output = getWantedOutput(list1, list2)
print(wanted_output)
>>> [3, 4, 5, 2, 1, 6, 7, 8, 9]
与其他给定答案相比,这种方法可读性较差,但如果列表较长,则会更快
wanted_output = []
for item in list1:
try:
wanted_output.append(list2.index(item))
except ValueError: # item not in list2
continue
对于长列表,最有效的解决方案是预处理第二个列表并将其转换为字典,其中列表项是键,位置是值。然后从该字典的第一个列表中查找元素:
positions = {item: pos for pos, item in enumerate(list2)}
[positions[item] for item in list1]
#[3, 4, 5, 2, 1, 6, 7, 8, 9]
如果您创建一个辅助
集合(列表2)
,并检查集合中的成员资格,而不是列表中的成员资格,则可以使解决方案更快。这将导致进一步的内存和时间成本,只有当列表2
非常大时,这可能才会摊销。@zr0gravity7由于构建集合是一个O(N)值,因此不需要额外的时间操作和集合查找是O(1)操作,但列表查找是O(N)操作。“集合查找是O(1)操作”不知道这一点。很高兴知道。这和你发布的被接受的答案都很好。
positions = {item: pos for pos, item in enumerate(list2)}
[positions[item] for item in list1]
#[3, 4, 5, 2, 1, 6, 7, 8, 9]