如何使用f字符串对齐列表



如何打印函数的每个递归(以快速排序为例(,如下所示:

[0]   1   [5, 3, 99, 22, 24, 11, 303, 3821]
[3]   5   [99, 22, 24, 11, 303, 3821]
[22, 24, 11]   99  [303, 3821]    
[11]   22  [24]           
[]   303 [3821]     

而不是这个:

[0]     1     [5, 3, 99, 22, 24, 11, 303, 3821]
[3]     5     [99, 22, 24, 11, 303, 3821]
[22, 24, 11]     99     [303, 3821]
[11]     22     [24]
[]     303     [3821]

应该用f字符串来完成吗?也许是用另一种方式?

def quicksort(values):
if len(values) <= 1:
return values
pivot = values[0]
less_than_pivot = []
greater_than_pivot = []
for value in values[1:]:
if value <= pivot:
less_than_pivot.append(value)
else:
greater_than_pivot.append(value)
print(f"{less_than_pivot}     {pivot}     {greater_than_pivot}")
return quicksort(less_than_pivot) + [pivot] + quicksort(greater_than_pivot)

numbers = [1, 5, 0, 3, 99, 22, 24, 11, 303, 3821]
sorted_numbers = quicksort(numbers)

您可以使用:

print(f"{str(less_than_pivot): >25} {str(pivot): >4}   {greater_than_pivot}")

请注意,可能很难预测字符串的最大长度,因此最简单的方法可能是使用一个合理的值。为此,您可以考虑中间列表的预期最大长度和所包含元素的长度。

输出:

[0]    1   [5, 3, 99, 22, 24, 11, 303, 3821]
[3]    5   [99, 22, 24, 11, 303, 3821]
[22, 24, 11]   99   [303, 3821]
[11]   22   [24]
[]  303   [3821]

最新更新