1

如何对字典的元素进行排序:

with open('directory file txt','r') as f:
     for line in f:
              keys = line.strip().split('.')
              value = keys[-1]
              for key in reversed(keys[1:-1]):
                     value = {key: value}
              result[keys[0]]=value

现在如果打印键我有这个:

['a','b','c','d','1']
['a','f','e','d','3']
['f','b','c','d','2']
['a','b','c','d','0']

我可以按最后一个元素对每个元素进行排序并将其保存到文件中吗?所以我的输出将是:

a.b.c.d.0
a.b.c.d.1
f.b.c.d.2
a.f.e.d.3
4

1 回答 1

1

你不需要字典。您可以将其中的行作为列表读取:

with open('directory file txt','r') as f:
    lines = f.readlines()

然后通过指定排序键直接对列表进行排序:

lines.sort(key = lambda s: int(s.rsplit('.', 1)[1]))
于 2012-11-30T16:55:30.533 回答