【发布时间】:2014-04-03 10:51:32
【问题描述】:
我正在尝试将单词对象(由扫描的单词、其按字母顺序排列的版本及其长度组成)按长度排序到列表中。因此,我初始化了一个长度为 0 的列表,并在浏览输入文件时对其进行了扩展。我想在列表中创建一个列表,以便我的结果 [5] 包含长度为 5 的列表。我该怎么做?
我首先将我的列表初始化如下:
results = []
然后我逐行扫描输入文件,创建临时对象,并希望将它们放入相应的列表中:
try: #check if there exists an array for that length
results[lineLength]
except IndexError: #if it doesn't, create it up to that length
# Grow the list so that the new highest index is len(word)
difference = len(results) - lineLength
results.extend([] for _ in range(difference))
finally:
results[lineLength].append(tempWordObject)
我觉得以下至少一项需要修改
(1) 我初始化结果列表的方式 (2) 我将对象附加到列表的方式 (3) 我扩展列表的方式(虽然我认为那部分是对的)
我正在使用 Python 3.4。
编辑:
from sys import argv
main, filename = argv
file = open(filename)
for line in file: #go through the file
if line == '\n': #if the line is empty (aka end of file), exit loop
break
lineLength = (len(line)-1) #get the line length
line= line.strip('\r\n')
if lineLength > maxL: #keeps track of length of longest word encountered
maxL = lineLength
#note: I've written a mergesort algorithm in a separate area in the code and it works
tempAZ = mergesort(line) #mergesort the word into alphabetical order
tempAZ = ''.join(tempAZ) #merges the chars back together to form a string
tempWordObject = word(line,tempAZ,lineLength) #creates a new word object
try: #check if there exists an array for that length
results[lineLength]
except IndexError: #if it doesn't, create it up to that length
# Grow the list so that the new highest index is len(word)
difference = len(results) - lineLength
results.extend([] for _ in range(difference))
print("lineLength: ", lineLength, " difference:", difference)
finally:
results[lineLength].append(tempWordObject)
编辑:
这是我的单词类:
class word(object): #object class
def __init__(self, originalWord=None, azWord=None, wLength=None):
self.originalWord = originalWord
self.azWord = azWord
self.wLength = wLength
编辑:
这里是对我想要实现的目标的说明:当我遍历一个(长度未知的)单词列表(长度也未知)时,我正在创建包含单词的单词对象,它按字母顺序排列版本及其长度(例如 dog、dgo、3)。当我浏览该列表时,我希望所有对象都进入另一个列表 (results[]) 中的列表,该列表由单词的长度索引。如果 results[] 不包含这样的索引(例如 3),我想扩展 results[] 并在 results[3] 中启动一个列表,其中包含单词 object(dog、dgo、3)。最后,results[] 应该包含按长度索引的单词列表。
【问题讨论】:
-
你能举一个你的出发点的例子吗?有点不清楚你的意思
-
快速浏览一下您的代码,您将无法处理相同长度的行。还有
tempWordObject是什么?你得到了损坏的代码。 -
@wnnmaw 我已经编辑了我的帖子,现在它包含了其余的代码。这更有意义吗?
-
@Michi 也许您可以更清楚地知道您的问题是什么,以及您的限制是什么。您可能会发现this 很有用。
-
@Michi 1. 编辑问题,不要只评论 2。这很好,但是有什么问题?你有错误吗?意外的输出?如果代码有效,但你认为它可以更整洁,这属于codereview.stackexchange.com
标签: python list python-3.x