考虑列表和列表的子集,如下所示:
v = [1,2,4,5,2,8,1] (index = 0,1,2,3,4,5,6,7)
v_sub = [1,2,8,4,1] (corresponding index in v = 0,1,6,2,7)
我这样编码:
v_sub.sort(key=v.index) #Or v_sub.sort(key=lambda x: v.index(x))
print(v_sub) #[1, 1, 2, 4, 8]
我想用v中的相应索引对v_sub进行排序。这意味着[0,1,2,6,7]。所以我认为它会给我[1,2,4,8,1但它没有。我怎样才能以简洁的方式纠正我的代码?
答案 0 :(得分:2)
您在 v 中有重复的值,因此您需要在使用它们时立即标记每个值:
v = [1,2,4,5,2,8,1]
v_sub = [1,2,8,4,1]
def indexAndClear(v, x):
i = v.index(x)
v[i] = None # This index should not be returned a second time
return i
vCopy = v[:] # to make sure we do not mutate v in the process
v_sub.sort(key=lambda x: indexAndClear(vCopy, x))
print(v_sub)