我有一个包含以下内容的列表:
lst = [[1, 'FANTASTIC FOUR'],[18, 'PADDINGTON'],[20, 'FANTASTIC FOUR']]
我正在使用基数排序对上面的lst中的字符串元素进行排序。
我想要实现的输出是:
lst = [[1,'FANTASTIC FOUR'],[20,'FANTASTIC FOUR'],[18,'PADDINGTON']]
由于第一个列表和最后列表 共享相同的字符串,因此它们应组合在一起 。
我尝试过写一个基数排序函数来满足这个要求,但我得到了输出:
lst = [[1, 'FANTASTIC FOUR'],[18, 'PADDINGTON'],[20, 'FANTASTIC FOUR']]
而不是:
lst = [[1,'FANTASTIC FOUR'],[20,'FANTASTIC FOUR'],[18,'PADDINGTON']]
以下是代码:
def radix_sort(lst, length):
for i in range (length-1, -1, -1): #for every letter "column"
buckets = [[], [], [], [], [], [], [], [], [], [], [], [], [],
[],[], [], [], [], [], [], [], [], [], [], [], []]
j = 0
for word in lst:
index = ord(word[j])-ord('A')
buckets[index].append(word) #add to bucket
lst[:] = [] #rebuild list
for containedList in buckets:
lst.extend(containedList)
return lst
lst = [[1, 'FANTASTIC FOUR'],[18, 'PADDINGTON'],[20, 'FANTASTIC FOUR']]
n = len(lst)
radix = [radix_sort(i, n) for i in lst]
print(radix)