【发布时间】:2014-04-03 17:21:44
【问题描述】:
注意:我使用的是 python 3。
我正在尝试按字母顺序对单词列表进行排序。
这是我喜欢的类型:
def radix_sort(List, length):
buckets = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
for i in range (length-1, -1, -1): #for every letter "column"
for word in List: #for every word
index = ord(word.azWord[i])-ord('a') #get the index of the word
buckets[index].append(word) #add word object to correct bucket
List[:] = []
for containedList in buckets:
List.extend(containedList)
它正在这个循环中使用:
for x in range(0,maxL):
radix_sort(results[x], x)
maxL 是我拥有的最长单词的长度,因此从 0 迭代到 maxL 会遍历整个列表。
我的列表结果[] 是一个列表列表。结果中的每个列表都包含一个单词对象,描述如下:
class word(object): #object class
def __init__(self, originalWord=None, azWord=None, wLength=None):
self.originalWord = originalWord
self.azWord = azWord
self.wLength = wLength
例如,results[3] 应该包含 wLength 为 3 的所有单词的列表。
当我为整个程序提供以下输入时:
hello
world
alphabetical
dog
cat
potato
stack
有了这段代码:
for row in results:
for item in row:
print(item.originalWord)
打印出来:
cat
cat
dog
dog
dog
cat
stack
stack
world
hello
hello
stack
hello
hello
world
hello
world
world
stack
stack
world
potato
potato
potato
potato
potato
potato
alphabetical
我很确定我在打印时正确地遍历了 results[]。为什么我的 radix_sort 没有给我正确的结果?我尝试使用调试器,但没有成功。
编辑:我将代码更改为如下:
def radix_sort(List, length):
for i in range (length-1, -1, -1):
for word in List:
buckets = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
index = ord(word.azWord[i])-ord('a')
buckets[index].append(word)
List[:] = []
for containedList in buckets:
List.extend(containedList)
return List #returns an alphabetized list
现在这里给我一个错误:
for containedList in buckets:
它说“UnboundLocalError:分配前引用的局部变量'buckets'”。这是什么意思?
【问题讨论】:
-
buckets[index].append(word)您将每个单词length次附加到存储桶中。 -
天哪。你是对的。
-
基本上,您需要将
buckets创建移动到第一个循环中,以及List重建。 -
如果我只是将
List[:] = []推入for word in List循环,它似乎工作正常。有什么理由我应该移动我丢失的buckets? -
看我的回答。你的 buckets 声明现在循环太深了,你的 List 重建没有移动。
标签: python sorting python-3.x radix-sort