我有一段代码应该按照文件的大小创建和排序文件列表。在这里:
class DataScript(object):
def __init__(self, index, name, size):
self.index = index
self.name = name
self.size = size
def __cmp__(self, other):
if hasattr(other, 'getKey'):
return self.getKey().__cmp__(other.getKey())
def getKey(self):
return self.size
def __iter__(self):
return self
def __next__(self):
self.index += 1
try:
return data[self.index - 1]
except IndexError:
self.idx = 0
raise StopIteration # Done iterating.
resultList = []
data = [d for d in os.listdir(dirpath) if '_DATA_TABLE' in d]
i=0
for file in data:
fileinfo = os.stat(join(dirpath, file))
file_obj = DataScript(i, file, float(fileinfo.st_size))
if isinstance(file_obj, DataScript):
resultList.extend(file_obj)
i=i+1
items = resultList
for i in range(len(items)):
for j in range(len(items) - 1 - i):
item1 = items[j]
item2 = items[j+1]
if isinstance(item1, DataScript) and isinstance(item2, DataScript):
if item1.__cmp__(item2)>0:
items[j] = item2
items[j+1] = item1
resultList = items
一切正常,但并不完全符合预期。最后的结果列表不是DataScript对象的排序列表,而是字符串。为什么呢 结果,我的排序末尾不起作用。
答案 0 :(得分:0)
您可能打算用append
而不是extend
:
for file in data:
fileinfo = os.stat(join(dirpath, file))
file_obj = DataScript(i, file, float(fileinfo.st_size))
if isinstance(file_obj, DataScript):
resultList.append(file_obj) # append DataScript obj to your list
i=i+1