tor*_*ger 1 python arrays hash dictionary
从目录列表中转储的示例:
hello:3.1 GB
world:1.2 MB
foo:956.2 KB
Run Code Online (Sandbox Code Playgroud)
以上列表的格式为FILE:VALUE UNIT.如何根据文件大小订购上面的每一行?
我想也许可以通过模式":VALUE UNIT"(或以某种方式使用分隔符)解析单元的每一行,然后通过ConvertAll引擎运行它,从字节中接收每个值的大小,用其余的行哈希(文件名),然后通过大小对结果字典对进行排序.
麻烦的是,我不知道模式匹配.但是我看到你可以对字典进行排序
如果有更好的方向来解决这个问题,请告诉我.
编辑:
我的列表实际上是在一个文件中.从(令人敬畏的)Alex Martelli的答案中获取灵感,我写了以下代码,从一个文件中提取,命令并写入另一个文件.
#!/usr/bin/env python
sourceFile = open("SOURCE_FILE_HERE", "r")
allLines = sourceFile.readlines()
sourceFile.close()
print "Reading the entire file into a list."
cleanLines = []
for line in allLines:
cleanLines.append(line.rstrip())
mult = dict(KB=2**10, MB=2**20, GB=2**30)
def getsize(aline):
fn, size = aline.split(':', 1)
value, unit = size.split(' ')
multiplier = mult[unit]
return float(value) * multiplier
print "Writing sorted list to file."
cleanLines.sort(key=getsize)
writeLines = open("WRITE_OUT_FILE_HERE",'a')
for line in cleanLines:
writeLines.write(line+"\n")
writeLines.close()
Run Code Online (Sandbox Code Playgroud)
Ale*_*lli 10
thelines = ['hello:3.1 GB', 'world:1.2 MB', 'foo:956.2 KB']
mult = dict(KB=2**10, MB=2**20, GB=2**30)
def getsize(aline):
fn, size = aline.split(':', 1)
value, unit = size.split(' ')
multiplier = mult[unit]
return float(value) * multiplier
thelines.sort(key=getsize)
print thelines
Run Code Online (Sandbox Code Playgroud)
['foo:956.2 KB', 'world:1.2 MB', 'hello:3.1 GB']
根据需要发出.mult
如果KB,MB和GB当然不会耗尽您感兴趣的单位集,则可能需要添加一些条目.
归档时间: |
|
查看次数: |
1337 次 |
最近记录: |