[英]Python casting and strange type convertion
I have a piece of code which is supposed to create and sort the list of file by their size. 我有一段代码应该按照文件的大小创建和排序文件列表。 Here it is: 这里是:
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
Everything works but not exactly as expected. 一切正常,但不完全符合预期。 The result list at the end is not sorted list of DataScript objects but strings. 最后的结果列表不是DataScript对象的排序列表,而是字符串。 Why ? 为什么呢 As an effect my sorting piece at the end doesn't work. 结果,我的排序末尾不起作用。
You probably meant to append
instead of extend
: 您可能打算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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.