有一堆问题的措辞类似,但我无法找到一个真正符合我预期语义的问题。
有两个列表,A
and B
,我想重新排列B
因此它的相对顺序与A
- 的最大元素B
与最大元素的当前位置相同A
,最小元素也是如此,依此类推。
注意A
未排序,我也不希望如此。
例如,如果输入以下内容:
a = [7, 14, 0, 9, 19, 9]
b = [45, 42, 0, 1, -1, 0]
我想要的输出是[0, 42, -1, 0, 45, 1]
.
请注意,预期的输出不是[0, 45, 1, 0, 42, -1]
,这就是你将两者压缩并排序的结果A
并获取结果元素B
(这是我看过的所有其他问题想要的)。
这是我的代码:
def get_swaps(x):
out = []
if len(x) <= 1:
return out
y = x[:]
n = -1
while len(y) != 1:
pos = y.index(max(y))
y[pos] = y[-1]
y.pop()
out.append((pos, n))
n -= 1
return out
def apply_swaps_in_reverse(x, swaps):
out = x[:]
for swap in swaps[::-1]:
orig, new = swap
out[orig], out[new] = out[new], out[orig]
return out
def reorder(a, b):
return apply_swaps_in_reverse(sorted(b), get_swaps(a))
该方法基本上是构建排序所需的交换列表A
通过选择排序、排序B
,然后反向应用这些交换。这可行,但速度相当慢(而且也相当令人困惑)。有更好的方法吗?