我想对列表进行排序并观察/可视化 Python 的排序算法Timsort如何移动元素。
第一次尝试:list每次更改后都会打印自己的子类:
class List(list):
def __setitem__(self, index, value):
list.__setitem__(self, index, value)
print(self)
Run Code Online (Sandbox Code Playgroud)
这在我自己更改元素时有效,但在sort...期间没有:
>>> a = List([None] * 2)
>>> a[0] = 'S'
['S', None]
>>> a[1] = 'P'
['S', 'P']
>>> a.sort()
>>>
Run Code Online (Sandbox Code Playgroud)
第二次尝试:a在每次比较元素时打印列表(在全局变量中):
class Str(str):
def __lt__(self, other):
print(a)
return other > self
Run Code Online (Sandbox Code Playgroud)
那确实有些作用,但列表总是......空的?
>>> a = list(map(Str, 'test'))
>>> a.sort()
[]
[]
[]
[]
[]
[]
>>>
Run Code Online (Sandbox Code Playgroud)
为什么这些尝试会失败,有没有办法观察 Timsort 正在做什么?